【发布时间】:2016-04-14 11:18:32
【问题描述】:
我已经看到了很多关于这个的问题,但没有一个包含关于如何为这个特定用例编译代码的解释。我运行以下命令:g++ main.cpp c.cpp testobj.cpp -o main,但运行它会给我一个Segmentation fault (core dumped)。当我在main.cpp 的main 方法中有打印语句并删除所有TestObj 代码时,它确实有效。
这是分配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";
}
testobj.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;
}
【问题讨论】:
标签: c++ namespaces