结构体重复定义
在 VS2005 下
我建立了一个头文件 Test.h
两个源文件分别为 Test.cpp 和 Keke.cpp
两个源文件都包含头文件 Test.h
各个文件的代码如下:
//Test.h
#ifndef TEST_H
#define TEST_H
extern struct Test
{
int x;
int y;
} test;
#endif
// Test.cpp
#include "stdafx.h"
void Init()
{
Test ts1;
ts1.x = 1;
ts1.y = 2;
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
// Keke.cpp
#include "stdafx.h"
void Init()
{
Test tx;
tx.x = 1;
tx.y = 2;
}
stdafx.h 头文件中包含了 Test.h 头文件
当我生成工程的时候
就出现了如下的错误:
stdafx.obj : error LNK2005: "struct Test test" (?test@@3UTest@@A) 已经在 Keke.obj 中定义
Test.obj : error LNK2005: "struct Test test" (?test@@3UTest@@A) 已经在 Keke.obj 中定义
d:\My Documents\Visual Studio 2005\Projects\Test\Debug\Test.exe : fatal error LNK1169: 找到一个或多个多重定义的符号
在结构体前面加上 extern 关键字或者 static 关键字
生成就可以成功了