我刚刚创建了某种库来自动化一些 C++ 的东西,问题是,一个文件包含一个带有函数的命名空间,而另一个文件包含一个尝试调用该函数的类。
编译器说该函数未定义。
文件1.cpp
namespace cs{
void func(){
//dosomething
}
}
文件2.cpp
class cx{
private:
void custom(){
cs::func(); //Compiler says "cs" has not been declared.
}
}
请帮忙。
您在
cs::func()
中缺少 File2.cpp
的声明,例如:
文件2.cpp
namespace cs{
void func();
}
class cx{
private:
void custom(){
cs::func();
}
}
这将使编译器知道该函数存在于
File2.cpp
中,并且只要编译并链接这两个 .cpp
文件,链接器就能够找到该函数。
也就是说,最好将该函数声明移至
.h
文件中,然后您可以在需要时 #include
,例如:
文件1.h
namespace cs{
void func();
}
文件1.cpp
#include "File1.h"
namespace cs{
void func(){
//dosomething
}
}
文件2.cpp
#include "File1.h"
class cx{
private:
void custom(){
cs::func();
}
}