2

I have downloaded code written in C, I've written a CMakeLists.txt to access it through Eclipse and it works fine and compiles.

My personal code is written in C++. I want to call the C code from it, and I've also created the CMakeLists.txt that takes into account where the C code is.

When I build my project there's no problem, as long as I don't do the following instruction :


// In one of my project's .cpp :

#ifdef __cplusplus
   extern "C" {
#endif
   #include "C_header_file_I_need.h"
#ifdef __cplusplus
}
#endif

// Core of the .cpp


The errors given tell me that the program is attempting to compile the C code with the C++ compiler and therefore :

  • nested functions

  • void*

  • ...

are not accepted by the compiler.

I've considered adapting the C program, but it is a lot of work ...

Since it's one compiler per CMakeLists, I was wondering how I could be able to compile the two parts of my project independently and the link them, by using CMakeLists (because I need it to work on any platform).

Thank you for you help, and do not hesitate to tell me what file/log you would need to look at.

  • 1
    maybe make the c into a shared library / dll? – Dory Zidon Jun 10 '15 at 16:42
  • 5
    Compile C code in C mode, then combine C and C++ at link time. If you use gcc, you can add a compiler option `-std=C99` or equivalent to force some source files be compiled as in C99 mode. – user3528438 Jun 10 '15 at 16:43
  • 3
    Nested functions aren't part of C either. That's a gcc extension (and insane). – EOF Jun 10 '15 at 16:43
  • 1
    related: [Compiling C and C++ files together using GCC](http://stackoverflow.com/questions/5430688/compiling-c-and-c-files-together-using-gcc) – NathanOliver Jun 10 '15 at 16:44
  • I did indicate that the c program in the target_link_libraries(...) part. I actually did not need to do the compiling myself, CMakeLists knew how to handle the two seperate parts ... For some reason it works know, and the only think I am sure I've changed is that the main function (for the C code) is in a .c file and not a .h file. The thing is, I do not call this function in my c++ code (otherwise I'd have two mains) ... So I do not how it can work ... Thanks for your help guys !! – Frederic Loge Jun 11 '15 at 13:39

1 Answers1

0

If you're only using the C functions in C++ and not the other way around, you could compile them all separately into object files (.o) and then link them together in a separate step. Keep in mind that the extern "C" is still required in your C++ code for this to work.

gcc -o foo.o foo.c
g++ -o bar.o bar.cpp

gcc -o final_build foo.o bar.o

(CMake does this automatically based on file extensions, if you would be interested in automating this)

EDIT: I hadn't realized that the comments already said all of this when I posted this.