Mixing C and C++ with CMAKE

28,731

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

CMake should utilise the relevant compiler and linker specified by the file extensions. In the instance where you are compiling and linking into an executable using a combination of C and C++, you would say:

add_executable(MyEXE main.cpp myFile.c)

I'd like to add a painfully trivial point.

In this instance, you must ensure that your project has the correct language name arguments, namely 1:

project(MyProject C CXX)

This should be done automatically when adding a CMake file, but depending on the order you added the files, the arguments might only include C or CXX.

If you only had for instance C as a language argument and your int main() was in your main.cpp, your program entry point wont exist and your compiler will omit an error.


1 Or you may omit the language arguments in which case the default arguments of C and CXX is selected. See here

Solution 5

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.

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

Share:
28,731
Cartesius00
Author by

Cartesius00

Fun

Updated on April 26, 2021

Comments

  • Cartesius00
    Cartesius00 about 3 years

    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.