我有一个简单的、有代表性的 C 程序,存储在一个名为 hello.c
的文件中:
#include <stdio.h>
int main(void)
{
printf('Hello, world\n');
return 0;
}
在我的 Linux 机器上,我尝试用 gcc 编译程序:
gcc hello.c
返回错误:
undefined reference to "___gxx_personality_v0" ... etc
与been一样discussed之前在 C++ 的上下文中,这个问题出现在链接阶段,当 gcc 试图将 C 库链接到 C++ 程序时,从而给出错误。在 one of the answers ,有人提到扩展名确实很重要,并且 gcc 在编译 C 文件时需要 .c
扩展名,以及一些其他扩展名(例如 .cpp
) 编译 C++ 文件时。
问题:我如何设置 gcc 以使用文件扩展名来确定要使用的编译器,因为 gcc 在我的系统上似乎默认为 C++?仅通过文件扩展名指定语言似乎还不够。如果我使用 -x
标志指定语言,gcc 将按预期运行。
gcc -x c hello.c
最佳答案
通常,您让 make
决定。
GNU Make 内置了隐式规则,可以自动选择正确的编译器。
尝试使用这些内容的 Makefile:
all: some_file.o some_other_file.o
然后将 some_file.cpp
和 some_other_file.c
放在同一目录中,gnu make 会自动选择正确的编译器。链接器,您可能仍然需要自己提供。混合使用 C 和 C++ 时,通常最容易使用 g++ 进行链接,如下所示:
program.exe: some_file.o some_other_file.o
g++ -o $@ @^
这等同于:
program.exe: some_file.o some_other_file.o
g++ -o program.exe some_file.o some_other_file.o
关于c - 如何设置 gcc 以使用文件扩展名(.c 或 .cpp)来确定正确的编译器/链接器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14818466/