Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C and C++ with CMAKE

Tags:

c++

c

gcc

g++

cmake

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.

like image 641
Cartesius00 Avatar asked Nov 11 '11 16:11

Cartesius00


3 Answers

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

like image 65
Bort Avatar answered Nov 17 '22 00:11

Bort


CMake does this automatically. You can freely intermix both types of files in your CMakeLists.txt file:

. . .
add_executable(
    my_program
    code.cpp
    more_code.c
)

I do this all the time and it just works.

like image 12
Randall Cook Avatar answered Nov 17 '22 00:11

Randall Cook


You can set LANGUAGE property of your source files to "CXX". See documentation.

like image 6
arrowd Avatar answered Nov 17 '22 02:11

arrowd