小编ban*_*ban的帖子

如何避免多重定义链接错误?

除了将hello()函数移动到另一个源(.cpp)文件或重命名该函数.有没有其他方法可以避免链接错误?

staticLibA.h

#ifndef _STATIC_LIBA_HEADER
#define _STATIC_LIBA_HEADER

int hello(void);
int hello_staticLibA_only(void);

#endif
Run Code Online (Sandbox Code Playgroud)

staticLibA.cpp

#include "staticLibA.h"

int hello(void)
{
    printf("\nI'm in staticLibA\n");
    return 0;
}

int hello_staticLibA_only(void)
{
    printf("\nstaticLibA: hello_staticLibA_only\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

g++ -c -Wall -fPIC -m32 -o staticLibA.o staticLibA.cpp
ar -cvq ../libstaticLibA.a staticLibA.o
a - staticLibA.o
Run Code Online (Sandbox Code Playgroud)

staticLibB.h

#ifndef _STATIC_LIBB_HEADER
#define _STATIC_LIBB_HEADER

int hello(void);
int hello_staticLibB_only(void);

#endif
Run Code Online (Sandbox Code Playgroud)

staticLibB.cpp

#include "staticLibB.h"

int hello(void)
{
    printf("\nI'm in staticLibB\n");
    return 0;
}

int hello_staticLibB_only(void)
{
    printf("\nstaticLibB: hello_staticLibB_only\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出: …

c++ linux linker g++ multiple-definition-error

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

g++ ×1

linker ×1

linux ×1

multiple-definition-error ×1