gpt4 book ai didi

c - gcc:目标文件或库中的重复标识符

转载 作者:行者123 更新时间:2023-11-30 18:04:50 25 4
gpt4 key购买 nike

重复的标识符会被归档器和链接器忽略。仅当源文件或目标文件直接传递给 gcc 时才会检测到它们,gcc 会将多个定义视为错误。也应该如此。归档器/链接器只是忽略它们,我们最终在可执行文件中只得到一个标识符。它是哪一个取决于目标文件或库的传递顺序。下面是一个演示这一点的脚本。

有什么方法可以让归档器/链接器认为这是一个错误吗?或者有其他工具可以解决这个问题吗?

#!/bin/sh

dir=$(mktemp -d)
echo "Using temporary directory: $dir"
echo
cd "$dir"

create_lib()
{
lib=$1
shift
rm -f $lib
ar r $lib "$@" 2>/dev/null
}

make_file()
{
base=file$1
cat >$base.c <<-EOF
int f()
{
return $1;
}
EOF

gcc $base.c -o $base.o -c

create_lib lib$base.a $base.o
}

make_file 1
make_file 2

cat >main.c <<EOF
int main()
{
extern int f();
return f();
}
EOF

gcc main.c -omain.o -c

cat <<EOF
1. Passing duplicate functions to archiver in different order
produces no error, but different result:
EOF

create_lib libfile.a file1.o file2.o
gcc main.o libfile.a -omain
(echo -n "ar file1.o file2.o: "; ./main; echo $?)

create_lib libfile.a file2.o file1.o
gcc main.o libfile.a -omain
(echo -n "ar file2.o file1.o: "; ./main; echo $?)

echo

cat <<EOF
2. Passing duplicate libraries to linker in different order
produces no error, but different result:
EOF

gcc main.o libfile2.a libfile1.a -omain
(echo -n "gcc libfile2.a libfile1.a: "; ./main; echo $?)

gcc main.o libfile1.a libfile2.a -omain
(echo -n "gcc libfile1.a libfile2.a: "; ./main; echo $?)

示例输出:

Using temporary directory: /tmp/tmp.AaXzxGcSdd

1. Passing duplicate functions to archiver in different order
produces no error, but different result:
ar file1.o file2.o: 1
ar file2.o file1.o: 2

2. Passing duplicate libraries to linker in different order
produces no error, but different result:
gcc libfile2.a libfile1.a: 2
gcc libfile1.a libfile2.a: 1

最佳答案

我认为您可以通过传递给链接器的 --whole-archive 选项获得您想要的行为。来自 GNU ld 文档:

--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.

Two notes when using this option from gcc: First, gcc doesn't know about this option, so you have to use -Wl,-whole-archive. Second, don't forget to use -Wl,-no-whole-archive after your list of archives, because gcc will add its own list of archives to your link and you may not want this flag to affect those as well.

关于c - gcc:目标文件或库中的重复标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7316155/

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