[英]C++, array declaration, templates, linker error
我的軟件中存在鏈接器錯誤。 我正在基於h,hpp,cpp文件使用以下結構。 有些類是模板化的,有些則沒有,有些具有函數模板。 軟件包含數百個包含的類...
宣言:
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代表一個包含主類的文件。
使用外部鏈接聲明標頭中的vars
extern const char* vars[];
並在一個源文件中定義它
const char* vars[] = {"foo", "bar"};
注意const
,不建議使用從字符串文字到char*
的轉換。 您現在擁有的方式違反了“ 一個”定義規則 (您在包含標頭的每個翻譯單元中重新定義vars
)。
我認為您只需要在test.hpp
extern char *vars[];
...然后在test.cpp中
char *vars[] = { "first", "second"...};
我假設您沒有聲明兩個都名為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
的新版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.