[英]Using a namespace define in another `.cpp` file
我有这个,但我似乎无法正确包含名称空间。
主.cpp
#include <iostream>
int main()
{
my_space::Print(); // main.cpp:5:5: error: use of undeclared identifier 'my_space'
return 0;
}
其他类.cpp
#include <iostream>
namespace my_space {
int x, y;
void Print()
{
std::cout << "Hello from namespace my_space." << std::endl;
}
}
我尝试添加一个otherclass.h
with namespace my_space {};
在它和main.cpp
中包括#include "otherclass.h"
但这也没有用。
您需要将声明与定义分开。
您的声明如下所示:
namespace my_space {
void Print();
}
您的定义如下所示:
#include <iostream>
#include "my_space.h"
void my_space::Print() {
std::cout << "Hello from namespace my_space." << std::endl;
}
然后将#include "my_space.h"
添加到主文件中,以便它知道声明。 linker 将负责组合最终的可执行文件。
像x
和y
这样的东西需要更多的澄清,因为随意放置全局变量是自找麻烦。
保持 otherclass.cpp 文件不变。 看起来不错。
按照你说的做一个新的 otherclass.h 文件,但让它看起来像这样:
#pragma once
namespace my_space {
void Print();
}
然后像这样构建它(如果使用 GCC):
gcc -O2 -W -Wall -std=c++17 main.cpp otherclass.cpp -o testprogram
重要的是不要养成在 header 文件中编写所有 function 代码的习惯。 相反,学会隐藏你能隐藏的一切。 请注意,在我的示例中,我没有包括您的 x 和 y 变量。 如果你的程序的任何其他部分不需要这些,那么其他人就不需要知道它们了。
header 文件中的代码会向包含它的每个文件增加编译时间。 更糟糕的是,该代码可能需要更多 header 个文件来支持它。 必须为包含第一个 header 的每个 cpp 文件包含和编译它。
这可能会导致暴行,其中 500 个源文件每个都重建 Boost 的一半并无缘无故地包含 Windows.h。
在带有 main.cpp 的编译单元中,未声明名称my_space
。 所以编译器会报错。
您应该将多个编译单元使用的通用声明放在 header 中,并将此 header 包含在使用 header 声明的所有编译单元中。
至于命名空间,您可以将 function Print
的声明放在命名空间中,并将命名空间本身放在 header 中。或者您可以在命名空间中内联定义 function。
至于变量,您应该在命名空间中使用存储说明符extern
声明它们,或者也将它们声明为内联。
例如:
// a header with the namespace
namespace my_space {
inline int x, y;
inline void Print()
{
std::cout << "Hello from namespace my_space." << std::endl;
}
}
要么:
// a header with the namespace
namespace my_space {
extern int x, y;
void Print();
}
在最后一种情况下,变量和 function 的相应定义应放在某个 cpp 文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.