C++命名空间namespace分离声明、定义

正确的文件结构

namespace声明(.h文件)和定义(.cpp文件)的分离,而后在主流程(.cpp文件)里调用,正确的结构以下:
namespace.cpp:ios

#include <iostream>
#include "namespace.h"

namespace first {
    int f_int = 4;
    void f_func() {
        std::cout << "first namespace function" << std::endl;
    }
}

namespace.h:函数

#pragma once
#include <iostream>

namespace first {
    extern int f_int;
    void f_func();
}

main.cpp:spa

#include <iostream>
#include "namespace.h"
void f_func(void);

namespace second {
    int s_int = 2;
}
int main() {
    using first::f_func;

    std::cout << second::s_int << std::endl;
    std::cout << first::f_int << std::endl;
    f_func();

    return 0;
}

void f_func(void) {
    std::cout << "main function" << std::endl;
}

输出:.net

2
4
first namespace function

分析

  • .h文件中仅声明code

    对变量的声明【 参考这里】: extern {类型} {变量名};

    😊难点1:变量如何仅声明
    错误的变量声明、定义分离后的报错blog

  • 在主流程.cpp文件里,最好在局部做用域里使用using。像上面这样的案例,在main函数外面using namesapce first;或者using first::f_func;,会致使和主流程.cpp文件里定义的全局函数f_func冲突。
    😊难点2:为啥我调用命名空间函数老是说不明确
    重复定义函数f_func
    函数名不明确的报错

总结

各类努力、规则都是为了管理名字,减小名字的污染。编译连接报“重复定义”的错,大概就是本身做用域弄乱了。作用域