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

正确的文件结构

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

#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:

#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;
}

输出:

2
4
first namespace function

分析

.h文件中仅声明

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

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

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

总结

各种努力、规则都是为了管理名字,减少名字的污染。编译链接报“重复定义”的错,大概就是自己作用域弄乱了。