我有一个 c 代码,可以在 Linux 中使用 gcc 编译。但是当我尝试使用 microsoft visual studio c++ 2008 express edition 编译它时,使用 ide,它显示错误
vec.obj : error LNK2005: _INIT_SETA already defined in a.obj
fatal error LNK1169: one or more multiply defined symbols found
我检查了头文件,它们都有预处理器防护以防止头文件被多次包含,例如
#ifndef _vec_h_
#define _vec_h_
然后我尝试在 visual studio 命令提示符下编译它,
cl main.c
可以编译。问题是什么?
最佳答案
我检查了头文件,它们都有预处理器防护以防止头文件被多次包含
这只会防止预处理器在单个编译单元(cpp 文件)中多次包含单个头文件。因此,您仍然在两个 cpp 文件中包含该 header ,并且该 header 定义了一个 _INIT_SETA 对象。如果 header 仅包含声明而不包含定义,则可以避免该问题。 (没有函数代码,也没有全局变量。)
Hpp 文件:
#ifndef _vec_h_
#define _vec_h_
class vector {
function(); //function prototype. No definition
}; //class declaration. No instantiation
extern vector myvector; //variable declaration. No instantiation
#endif //_vec_h_
Cpp文件:
#include "vec.h"
vector::function() {} //function definition only in this cpp file
vector myvector; //variable instantiation only in this cpp file
唯一的异常(exception)通常是模板,它完全在头文件中,链接器自己解决。
关于c++ - 无法使用 Microsoft Visual Studio C++ 2008 速成版编译 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7502750/