c++ - 无法使用 Microsoft Visual Studio C++ 2008 速成版编译 C 代码

标签 c++ c visual-studio-2008 compiler-errors

我有一个 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/

相关文章:

c++ - qt exe文件不运行

c++ - 类中的 ofstream - 试图引用已删除的函数

c++ - 优先队列排序 [C++]

c++ - 具有 SOAP 请求/响应支持的最佳 XML 解析器

c - Realloc 现有数据丢失

c# - VS 2008 查找/替换为折叠区域

c++ - C++中上限函数的问题

c++ 将各种参数传递给父类构造函数(线程c++11)

c - 如何为具有 SRC、OBJ 和 BIN 子目录的 C 项目创建 Makefile?

c# - 索引超出范围。必须是非负数且小于集合的大小