开发者

Can CMake use g++ to compile C files?

开发者_如何学运维

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.


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:

set_source_files_properties(filename.c PROPERTIES LANGUAGE CXX )


To have cmake treat all C files as C++ files use:

file(GLOB_RECURSE CFILES "${CMAKE_SOURCE_DIR}/*.c")
SET_SOURCE_FILES_PROPERTIES(${CFILES} PROPERTIES LANGUAGE CXX )


If you need to switch the whole project, set it in the project directive:

project(derproject LANGUAGES CXX)


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

set(qpid_dispatch_SOURCES
  alloc.c
  alloc_pool.c
  aprintf.c
  amqp.c
  atomic.c
# [...]
)
set_source_files_properties(${qpid_dispatch_SOURCES} PROPERTIES LANGUAGE CXX)
add_library(qpid-dispatch OBJECT ${qpid_dispatch_SOURCES})

As described in the linked docs, CMake 3.18 changed the scoped effect of set_source_files_properties. See the DIRECTORY and TARGET_DIRECTORY options. Therefore, to apply source file property recursively to all files in your project, your CMakeLists.txt should look something like this

cmake_minimum_required(VERSION 3.20)
project(qpid-dispatch LANGUAGES C CXX)

# [...]

add_subdirectory(src)
add_subdirectory(tests)
add_subdirectory(router)

# [...]

file(GLOB_RECURSE CFILES "*.c")
set_source_files_properties(${CFILES}
        DIRECTORY src tests router
        PROPERTIES LANGUAGE CXX)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜