在单独的标头中使用结构时链接错误

时间:2019-05-25 16:04:21

标签: c++ struct static const linker-errors

这是某些代码的简化版本。

  1. structroughStruct.h中定义。它有一个static const char * someVarsomeVar在同一文件的struct外部初始化。

  2. 另一个class roughParse(在roughParse.h中定义并在roughParse.cpp中实现)打算利用roughStruct(出于此问题的目的,它绝对不起作用)

  3. 主文件roughMain.cpp打算利用class roughParsestruct roughStruct上工作。(同样,它什么也不做。)

代码无法编译。

  1. 据我所知,由于roughStructinclude中的roughMain.cpp都在roughParse.cpp中,因此发生了错误。 我需要在此处进行说明 -由于下一点,我感到困惑。
  2. 经过多次试验和错误,以下是纠正错误:
//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

0 个答案:

没有答案