c++ - 为什么对 c 和 c++ 使用 gcc 和 g++ 编译器驱动程序

标签 c++ c gcc g++

我已经将一个项目移植到 arm cortex M7 芯片上,这是我第一次使用 makefile,我使用的是 gnu-gcc 编译器集合。

是否建议使用 gcc 驱动程序编译“c”代码,然后使用 g++ 驱动程序编译“c++”(app)代码,然后链接。 c 代码都是低级(头文件)寄存器访问地址等,不包含函数(还)或附加的源文件。

或者如果头文件可以修改为使用 g++ 编译(如果需要),我可以使用 g++ 编译器编译所有内容吗?

我已将其设置为 gcc 编译 c 文件,g++ 编译 c++ 并链接。

最佳答案

gcc 和 g++ 之间的唯一区别是:

  • 当驱动程序用于调用链接器时,g++ 会导致 libstdc++ 作为“stdlibs”的一部分进行链接,而 gcc 将仅链接 libc。
  • 除非指定了 -x 选项,否则 g++ 会将 .c、.h 和 .i 文件编译为 C++。

这两个驱动程序都将根据文件扩展名或命令行开关编译 C 或 C++。如果您仅为编译调用编译器驱动程序并使用 gccg++ -x 直接调用链接器 (ld),则使用哪个都没有区别。

同样,如果您为 C++ 代码调用 gcc 驱动程序并显式链接 stdlibc++,它也没有区别 - 只要您的 crt0.o 不是 C-only - C++ 运行时启动必须在 main() 之前调用全局静态构造函数) - 这很可能已经是这种情况。

来自 documentation 的最终词:

3.3 Compiling C++ Programs

C++ source files conventionally use one of the suffixes ‘.C’, ‘.cc’, ‘.cpp’, ‘.CPP’, ‘.c++’, ‘.cp’, or ‘.cxx’; C++ header files often use ‘.hh’, ‘.hpp’, ‘.H’, or (for shared template code) ‘.tcc’; and preprocessed C++ files use the suffix ‘.ii’. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).

However, the use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats ‘.c’, ‘.h’ and ‘.i’ files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a ‘.h’ extension for use in C++ compilations. On many systems, g++ is also installed with the name c++.

When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs. See Options Controlling C Dialect, for explanations of options for languages related to C. See Options Controlling C++ Dialect, for explanations of options that are meaningful only for C++ programs.

如果你只想使用一个,我建议你使用 gcc 并单独调用链接器或显式链接 -libstdc++。这样编译模式将取决于文件扩展名。使用 g++ -x 编译 C 代码只会引起困惑。

关于c++ - 为什么对 c 和 c++ 使用 gcc 和 g++ 编译器驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49873604/

相关文章:

c - 如何更改 objdump 输出格式?

c++ - const 是否引用了全局常量良好实践?

c++ - 标准功能要求

c - 在 C 中使用指向函数的指针调用函数

c - 纯C : trim all characters in a string after a word occurs

c - 对齐堆栈是什么意思?

gcc - 分析 ELF 二进制文件以最小化其大小

c++ - 如何将char数组连接成字符串

c++ - 编译器如何实现C++继承?

c++ - 将派生对象传递给模板