This is a simpified version of some code.
The
struct
is defined inroughStruct.h
. It has astatic const char * someVar
.someVar
is initialized outside thestruct
in the same file.Another
class roughParse
(defined inroughParse.h
and implemented inroughParse.cpp
) intends to make use ofroughStruct
(For the purposes of this questions it does absolutely nothing)- The main file
roughMain.cpp
intends to make use of theclass roughParse
to work onstruct roughStruct
.(Again here it does nothing.)
The code doesn't compile.
- As far I understand the error is occuring because
roughStruct
is beinginclude
in bothroughMain.cpp
androughParse.cpp
. I need clarification here--I am confused as to how that can be because of the next point. - After a lot of trial and error, the following corrects the error:
//defining the const inline and not outside
constexpr static const char *someVar="abcd";
or
//using constructor to initialize and not outside
roughStruct()
{
someVar="abcd";
}
Both approaches don't work forconst char *
replaced with const string
.
Why don't they?
How do you initialize a static const string
then?
The second approach doesn't seem ideal as structures are for holding data though I will use it if its the only way. But again, it doesn't solve the problem for strings.
But most importantly why do these modifications remove a linking error?
In regards to point 4, if the roughStruct
was being included twice, it would still be in the above solutions as they don't change any #include
directives. So point 4 is not the reason right?
Code:
The structure:
//roughStruct.h
#ifndef ROUGHSTRUCT_H
#define ROUGHSTRUCT_H
#include<string>
struct roughStruct {
//this is the critical thing
static const char *someVar;
// static std::string someStringVar;
};
const char *someVar = "abcd";
#endif //ROUGHSTRUCT_H
This is the parser class:
//roughParse.h
#ifndef ROUGHPARSE_H
#define ROUGHPARSE_H
#include "roughStruct.h"
class roughParse {
//had some code here that was implmented in roughParse.cpp
};
#endif //ROUGHPARSE_H
//roughParse.cpp
#include "roughParse.h"
#include<iostream>
using std::cout;
using std::endl;
//had some code here implementing roughParse.h
The main file:
//roughMain.cpp
#include "roughStruct.h"
#include "roughParse.h"
int main()
{
//had some code here that used roughparse and roughStruct
return 0;
}
CMakeLists.txt:
...
add_executable(
project
${SOME_DIR}roughMain.cpp
${SOME_DIR}roughParse.h
${SOME_DIR}roughParse.cpp
${SOME_DIR}roughStruct.h
)
...
CMake Error:
//ignore the line nos.
CMakeFiles/test/roughParse.cpp.o:project/test/roughStruct.h:13: multiple definition of `someVar'
CMakeFiles/test/roughMain.cpp.o:project/test/roughStruct.h:13: first defined here
Env
g++ (Ubuntu 7.4.0-1ubuntu1~18.04) 7.4.0
CMake: Version 3.14.3
IDE: CLion ver 2019.1.3