gpt4 book ai didi

c++ - 使用 GCC 链接具有重复类名的库

转载 作者:可可西里 更新时间:2023-11-01 15:25:03 30 4
gpt4 key购买 nike

在链接包含同名类的库时,GCC 是否有办法发出警告?例如

Port.h

class Port {
public:
std::string me();
};

Port.cpp

#include "Port.h"
std::string Port::me() { return "Port"; }

FakePort.h

class Port {
public:
std::string me();
};

FakePort.cpp

#include "FakePort.h"
std::string Port::me() { return "FakePort"; }

main.cpp

#include "Port.h"

int main() {
Port port;
std::cout << "Hello world from " << port.me() << std::endl;
return 0;
}

建筑

# g++ -c -o Port.o Port.cpp
# ar rc Port.a Port.o
# g++ -c -o FakePort.o FakePort.cpp
# ar rc FakePort.a FakePort.o
# g++ -c -o main.o main.cpp
# g++ main.o Port.a FakePort.a
# ./a.out
Hello world from Port

更改图书馆顺序

# g++ main.o FakePort.a Port.a
# ./a.out
Hello world from FakePort

根据 this page :

If a symbol is defined in two different libraries gcc will use the first one it finds and ignore the second one unless the second one is included in an object file which gets included for some other reason.

所以上面的行为是有道理的。不幸的是,我继承了一个相当大的代码库,它不使用 namespace (现在添加它们是不可行的)并且在多个库中使用一些通用类名。我想在链接时自动检测重复名称,以确保类的错误拷贝不会被意外实例化。像这样的东西:

# g++ -Wl,--warnLibraryDupSymbols main.o FakePort.a Port.a
Warning: Duplicate symbol: Port

但我在 GCC 链接器选项中找不到任何东西可以做到这一点。是否可以让 GCC 自动检测并报告此类情况?

最佳答案

以下可能值得一试(老实说,我不知道它是否会做你想做的事):

--whole-archive

For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally used to turn an archive file into a shared library, forcing every object to be included in the resulting shared library. This option may be used more than once.

我还没有尝试过,但听起来好像它会把库中的所有项目都作为目标文件拉入。您需要为每个库指定选项。

正如 Neil 所说,这不会给您带来类级别的冲突,但如果有具有相同签名的类成员,这可能会让链接器告诉您。

关于c++ - 使用 GCC 链接具有重复类名的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766022/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com