这是某些代码的简化版本。
struct
在roughStruct.h
中定义。它有一个static const char * someVar
。 someVar
在同一文件的struct
外部初始化。
另一个class roughParse
(在roughParse.h
中定义并在roughParse.cpp
中实现)打算利用roughStruct
(出于此问题的目的,它绝对不起作用)
roughMain.cpp
打算利用class roughParse
在struct roughStruct
上工作。(同样,它什么也不做。)代码无法编译。
roughStruct
和include
中的roughMain.cpp
都在roughParse.cpp
中,因此发生了错误。 我需要在此处进行说明 -由于下一点,我感到困惑。//defining the const inline and not outside
constexpr static const char *someVar="abcd";
或
//using constructor to initialize and not outside
roughStruct()
{
someVar="abcd";
}
两种方法均不适用于const char *
const string
。
为什么不呢?
然后如何初始化static const string
?
第二种方法似乎并不理想,因为结构是用于保存数据的,尽管我将使用它作为唯一方法。但是同样,它不能解决字符串问题。
但最重要的是为什么这些修改会消除链接错误?
关于第4点,如果将roughStruct
包含两次,则它们仍将在上述解决方案中,因为它们没有更改任何#include
指令。所以第4点不是正确吗?
代码:
结构:
//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
这是解析器类:
//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
主文件:
//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错误:
//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
环境
g ++(Ubuntu 7.4.0-1ubuntu1〜18.04)7.4.0
CMake:版本3.14.3
IDE:CLion版本2019.1.3