将 C 和 C++ 与 CMAKE 混合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8096887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mixing C and C++ with CMAKE
提问by Cartesius00
We write an application mainly in C
but some sub-modules are written in C++
(on Linux). The problem is how to write CMakeLists.txt
files to use g++
for some subdirectories and gcc
for another.
我们主要编写一个应用程序,C
但一些子模块是用C++
(在 Linux 上)编写的。问题是如何编写用于某些子目录和其他子目录的CMakeLists.txt
文件。g++
gcc
采纳答案by Bort
The compiler and linker is usually determined by the file extension if not set otherwise. So as long as the file endings are fine, your code is compiled and linked with the correct compiler.
如果没有另外设置,编译器和链接器通常由文件扩展名决定。因此,只要文件结尾没问题,您的代码就会被编译并与正确的编译器链接。
On a side note, remember to make the correct extern C declarations, if you mix C and C++.
附带说明一下,如果您混合使用 C 和 C++,请记住做出正确的 extern C 声明。
回答by Randall Cook
CMake does this automatically. You can freely intermix both types of files in your CMakeLists.txt file:
CMake 会自动执行此操作。您可以在 CMakeLists.txt 文件中自由混合两种类型的文件:
. . .
add_executable(
my_program
code.cpp
more_code.c
)
I do this all the time and it just works.
我一直这样做,它只是有效。
回答by arrowd
You can set LANGUAGE property of your source files to "CXX". See documentation.
您可以将源文件的 LANGUAGE 属性设置为“CXX”。请参阅文档。
回答by bames53
The difference between g++ and gcc is basically that g++ passes -lstdc++ to the linker. Just add the c++ standard library as an explicit dependency of the c++ modules.
g++ 和 gcc 的区别基本上是 g++ 将 -lstdc++ 传递给链接器。只需添加 c++ 标准库作为 c++ 模块的显式依赖项。
To be clear, gcc can compile C++ code. gcc and g++ are the same in this regard. The difference is only that when using g++ you don't have to explicitly tell the compiler to link to libstdc++.
需要明确的是,gcc 可以编译 C++ 代码。gcc 和 g++ 在这方面是相同的。区别仅在于在使用 g++ 时,您不必明确告诉编译器链接到 libstdc++。