C++链接错误.无效

C++ link error.. is invalid?

本文关键字:无效 错误 链接 C++      更新时间:2023-10-16

我一直收到这个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);
}