CMake 可以使用 g++编译C文件?
我曾参与过一个项目,其中使用 g++ 编译以 .c 结尾的文件中的 C 代码。原因是我被告知 g++ 有更好的警告消息。
我正在将该项目的构建过程切换为使用 CMake。我发现最初CMake想使用gcc来编译C文件。由于在使用时声明变量之类的原因,此操作失败了。 设置来使用g++编译C文件
set(CMAKE_C_COMPILER_INIT g++)
所以我尝试通过使用CMakeLists.txt文件中的 。但这会导致错误消息:
#error "The CMAKE_C_COMPILER is set to a C++ compiler"
我已将 .c 文件重命名为 .cpp 以解决此问题,因为这似乎是我使事情正常工作的最简单方法,也许也是最好的方法。但我想知道是否可以强制 CMake 使用 g++ 来编译 C 文件。
I have worked on a project where I was using g++ to compile C code in files that end in .c. The reason is that I'm told that g++ has better warning messages.
I am switching the build process for this project to use CMake. I found that initially CMake wanted to use gcc to compile C files. This failed because of things like declaring variables at use time. So I tried to use g++ to compile C files by using the setting
set(CMAKE_C_COMPILER_INIT g++)
in the CMakeLists.txt file. But this results in the error message:
#error "The CMAKE_C_COMPILER is set to a C++ compiler"
I have been renaming my .c files to .cpp to fix this problem as that seems to be the easiest way for me to make things work, and perhaps the best way too. But I was wondering if it is possible to force CMake to use g++ to compile C files.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不应该为此目的重写编译器。如果您确实需要将 C 文件编译为 C++,那么您应该告诉 cmake 您的文件属于 C++ 语言:
You should not override the compiler for this purpose. If you really need to compile your C files as C++ then you should teach cmake that your files belong to C++ language:
要让 cmake 将所有 C 文件视为 C++ 文件,请使用:
To have cmake treat all C files as C++ files use:
如果需要切换整个项目,请在项目 指令:
If you need to switch the whole project, set it in the project directive:
set_source_files_properties
这里(我)选择的 CMake 设置是
set_source_files_properties
命令。 https://cmake.org/cmake/help/latest/command/set_source_files_properties。正如链接文档中所述,CMake 3.18 更改了 set_source_files_properties 的范围效果。请参阅
DIRECTORY
和TARGET_DIRECTORY
选项。因此,要将源文件属性递归地应用于项目中的所有文件,您的CMakeLists.txt
应如下所示set_source_files_properties
The CMake setting of (my) choice here would be the
set_source_files_properties
command. https://cmake.org/cmake/help/latest/command/set_source_files_properties.htmlAs described in the linked docs, CMake 3.18 changed the scoped effect of set_source_files_properties. See the
DIRECTORY
andTARGET_DIRECTORY
options. Therefore, to apply source file property recursively to all files in your project, yourCMakeLists.txt
should look something like this