Can I compile .c and .cpp files seperately in a single project?


I am developing a C project. I have a library with .cpp files (No other option). But my project has most of .c files. Finally, I have to connect the different file types.

Whenever I build a project, I get compilation-level errors. My c project is not recognizing C++ keywords like class, virtual, new etc.

  1. Are there any commands or arguments from CMake to use .cpp files in the C project?
  2. Can I mention the C++ and c compilers to build respective files in a project?
  3. Do you have any solutions for this kind of problematic situation from CMake’s side?

I appreciate any help you can provide.

In your project() call, just add CXX to the LANGUAGES argument, like

project( foo
  DESCRIPTION "My annoying C and C++ project"

From there, CMake should automatically know that .c files are C code and .cpp files are C++ code.

According the documentation, C ad CXX are the default values.
I guess the problem won’t be solved.

What does your CMakeLists.txt look like?

From the project documentation:

LANGUAGES <language-name>...

Optional. Can also be specified without LANGUAGES keyword per the first, short signature.


By default C and CXX are enabled if no language options are given.

I had the opposite problem; a C++ project was not compiling a C file. In that case, I had LANGUAGES CXX (only). Adding C to the list fixed the problem.

Your issue doesn’t have to remain unsolved, but if there is some reason my solution won’t work, you’ll need to give us more information.