我已经看到很多关于此的问题,但没有包含关于如何编译这个特定用例的代码的解释。我运行以下命令:g++ main.cpp c.cpp testobj.cpp -o main
,但运行这给我一个Segmentation fault (core dumped)
。当我在main.cpp
的main
方法中有打印语句并删除所有TestObj
代码时,它确实起作用。命名空间中的C++全局变量
这是分配C::test
常量的正确方法吗?
main.cpp中:
#include "c.h"
#include "testobj.h"
TestObj testobj;
int main() {
return 0;
}
c.h:
#ifndef CONSTANTS
#define CONSTANTS
#include <string>
namespace C {
extern std::string test;
}
#endif
c.cpp:
#include "c.h"
namespace C {
std::string test = "test";
}
测试obj.h:
#ifndef TESTOBJ
#define TESTOBJ
class TestObj {
public:
TestObj();
};
#endif
testobj.cpp:
#include "testobj.h"
#include <iostream>
#include "c.h"
TestObj::TestObj() {
std::cout << C::test << std::endl;
}
我保存将'TestObj testobj'的声明更改为'TestObj * testobj',并通过执行'* testobj = TestObj()'将初始化移动到'main()'方法。 – martijnn2008
@ martijnn2008是的,如果你考虑使用指针安全。 :)所有全局变量初始化后,总是会调用main函数。 –