C++链接错误.无效
C++ link error.. is invalid?
我一直收到这个Visual C++2010 LNK2005链接器错误,说我对"error.h"中包含的两个函数有多个定义。(我为显示错误而制作的标题)
我的项目是这样的:
BaseImage.h
BaseImage.cpp --> includes BaseImage.h , Error.h
PNGImage.h --> includes BaseImage.h
PNGImage.cpp --> includes PNGImage.h , Error.h
main.cpp --> includes PNGImage.h
当然,错误。h:
/*
Optional macros:
AE_EXIT_AT_ERROR
*/
#pragma once
#include <stdexcept>
void aeError(const char *str, int code=1)
{
throw std::runtime_error(str);
#ifdef AE_EXIT_AT_ERROR
std::exit(code);
#endif
}
void aeAssert(bool b, const char *failStr = "assertion failed")
{
if(!b)
aeError(failStr);
}
我在每个头文件中都有#pragma once
,并尝试在Error.h中添加include保护。
以下是编译输出:
1>PNGImage.obj : error LNK2005: "void __cdecl aeError(char const *,int)" (?aeError@@YAXPBDH@Z) already defined in BaseImage.obj
1>PNGImage.obj : error LNK2005: "void __cdecl aeAssert(bool,char const *)" (?aeAssert@@YAX_NPBD@Z) already defined in BaseImage.obj
1>C:...Project.exe : fatal error LNK1169: one or more multiply defined symbols found
这可能是个bug吗?
在.h文件中定义函数时,请使它们内联。否则,函数定义是#include
的所有.cpp文件的对象代码的一部分,具有外部链接。
inline void aeError(const char *str, int code=1)
{
throw std::runtime_error(str);
#ifdef AE_EXIT_AT_ERROR
std::exit(code);
#endif
}
inline void aeAssert(bool b, const char *failStr = "assertion failed")
{
if(!b)
aeError(failStr);
}
另一种选择是在.h文件中声明函数,并在一个.cpp文件中定义它们。
.h文件:
extern void aeError(const char *str, int code=1);
extern void aeAssert(bool b, const char *failStr = "assertion failed");
.cpp文件:
// Don't use inline and don't include the default argument values.
void aeError(const char *str, int code)
{
throw std::runtime_error(str);
#ifdef AE_EXIT_AT_ERROR
std::exit(code);
#endif
}
void aeAssert(bool b, const char *failStr)
{
if(!b)
aeError(failStr);
}
相关文章:
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- what(): basic_string::_M_construct 空无效错误
- C++ Linux 运行时basic_string::_M_construct null 无效错误
- 调用boost v1.58中的函数时出现模板名称使用无效错误
- 对象分配-成员函数的使用无效错误
- 从 WindowsAPI 调用 NetLocalGroupAddMembers 时,安全 ID 结构无效错误
- 为什么映射迭代器显示基本操作数无效错误
- 获取数组类型的无效错误
- 调用 vector.erase() 函数时指针操作无效错误
- C++:basic_string::_M_construct 空,对于图形 BFS 算法无效错误
- C++运行程序后给我 basic_string::_S_construct null 无效错误
- 使用 std::vector 时抽象类类型"Shape"的新表达式无效错误
- mmap 错误:分段错误/指针无效错误
- 从字符到字符编译器的转换无效错误
- 恒常性添加无效?错误:无法使用字符**初始化常量字符**
- 二进制表达式的操作数无效错误消息
- "从'文件* {aka _iobuf}'到'int'的转换无效"错误
- 在 boost 中序列化二进制数据失败,并出现"签名无效"错误
- 基类 T 无效错误
- 从“常量字符*”到“字符*”的转换无效错误