I have seen a lot of questions on this, but none include explanation on how to compile the code for this specific use case. I run the following command: g++ main.cpp c.cpp testobj.cpp -o main
, but running this gives me a Segmentation fault (core dumped)
. When I have the print statement in the main
method in main.cpp
and remove all TestObj
code it does work.
Is this the proper way of assigning the C::test
constant?
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;
}