0

我的软件中有链接器错误。我正在使用以下基于 h、hpp、cpp 文件的结构。有些类是模板化的,有些不是,有些有函数模板。SW 包含数百个包含的类...

宣言:

test.h
#ifndef TEST_H
#define TEST_H

class Test
{
   public: 
        template <typename T>
        void foo1();

        void foo2 ();
};

#include "test.hpp" 

#endif

定义:

test.hpp
#ifndef TEST_HPP
#define TEST_HPP

template <typename T>
void Test::foo1() {}

inline void Test::foo2() {} //or in cpp file

#endif

CPP 文件:

test.cpp
#include "test.h"

void Test::foo2() {} //or in hpp file as inline

我有以下问题。变量 vars[] 在我的 h 文件中声明

test.h
#ifndef TEST_H
#define TEST_H

char *vars[] = { "first", "second"...};

class Test
{
    public: void foo();
};

#include "test.hpp"

#endif

并用作在 hpp 文件中作为内联定义的 foo() 方法内的局部变量。

test.hpp
#ifndef TEST_HPP
#define TEST_HPP


inline void Test::foo() {
    char *var = vars[0];   //A Linker Error
}

#endif

但是,会发生以下链接器错误:

Error   745 error LNK2005: "char * * vars" (?vars@@3PAPADA) already defined in main.obj

如何以及在何处声明 vars[] 以避免链接器错误?包括后

#include "test.hpp"

声明已经晚了……

正如我所写,该软件包含很多cpp,并且hpp文件相互包含(所有包含都已检查)。无法发送整个示例...

main.obj 代表一个包含主类的文件。

4

3 回答 3

3

vars使用外部链接在标题中声明

extern const char* vars[];

并将其定义在一个源文件中

const char* vars[] = {"foo", "bar"};

请注意const,从字符串文字到的转换char*已被弃用。你现在拥有它的方式,你违反了一个定义规则(你在vars你的标题包含的每个翻译单元中重新定义)。

于 2012-11-04T23:07:16.257 回答
2

我认为您只需要在 test.hpp

extern char *vars[];

...这在 test.cpp

char *vars[] = { "first", "second"...};
于 2012-11-04T23:06:11.470 回答
0

我假设您没有声明两个名为Test. 如果你是,那将给你带来无穷无尽的问题。你不能这样做。

所以我假设完整的声明class Test看起来像这样:

class Test
{
 public:
   void foo();

   template <typename T>
   void foo1();

   void foo2 ();
};

如果是这种情况,那么你的问题就很清楚了。

您需要更改vars. 你需要有这个test.h

extern char *vars[];

这在test.cpp

char *vars[] = { "first", "second"...};

否则编译器会认为你试图vars在每个文件中声明一个新版本。

于 2012-11-04T23:04:35.263 回答