Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add C++ code to C project

Tags:

c++

c

What I want to do:

I have autogenerated C Code generated with Matlab Simulink and want to enhance it with some more functionality written in C++. To be exact, the C code calls a C-style API that internally uses C++. The whole thing is in a VS 2008 C++ project.

The problem:

It compiles, as long as I tell VS to compile it as C and leave out my C++ code. As soon as I compile it as C++ problems arise.

First of all, I can't compile it as C++ because math.h produces an error C2668 due to an ambiguous call to an overloaded function (fabs()).

If I now additionally add some C++, e.g. include iostream, I get hundreds of compiler errors complaining about missing curly braces and misplaced colons somewhere in cstdlib.

My question:

How can I mix the two languages in a way that works? I read about preprocessor defines (http://www.parashift.com/c++-faq-lite/overview-mixing-langs.html) but I don't know how to apply them correctly to solve my problem.

Any help is greatly appreciated!

like image 497
fewu Avatar asked Oct 18 '13 12:10

fewu


1 Answers

It seems you are including C++ headers in your C source code. Probably indirectly by including it in other header files (i.e. the C source include your C++ header, and the C++ header includes other C++ header files).

There are two ways of solving this:

  1. Use the preprocessor to conditionally include the C++ headers only when compiled in C++. This can be done like

    #ifdef __cplusplus
    # include some_cpp_header
    #endif
    
  2. Don't include C++ headers (directly or indirectly) in your header files. Or better, make a separate header file whose only purpose is to be included in the C source, and which only contains the function prototypes (with extern "C" when compiled as C++) of the API. The body of the header file could look like this

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void function1(int);
    int function2(const char*);
    /* More function prototypes */
    
    #ifdef __cplusplus
    }
    #endif
    

I recommend the second method.

like image 142
Some programmer dude Avatar answered Sep 24 '22 15:09

Some programmer dude