Add C ++ Code to C Project

What I want to do:

I have auto-generated C code generated using Matlab Simulink, and I want to improve it with some functions written in C ++. More precisely, the C code calls the C API, which internally uses C ++. It's all about the VS 2008 C ++ project.

Problem:

It compiles while I say VS to compile it as C and leave my C ++ code. As soon as I compile it, since C ++ problems arise.

First of all, I cannot compile it as C ++, because math.h generates error C2668 due to the ambiguous call of the overloaded function (fabs ()).

If I now additionally add C ++, for example. including iostream, I get hundreds of compiler errors complaining about the absence of curly braces and unulocal colons somewhere in cstdlib.

My question is:

How can I mix two languages ​​the way it works? I read about the preprocessor ( http://www.parashift.com/c++-faq-lite/overview-mixing-langs.html ), but I don’t know how to use them correctly to solve my problem.

Any help is much appreciated!

+4
source share
2 answers

It seems you have included C ++ headers in your C source code. Perhaps indirectly by including it in other header files (i.e., Source C includes your C ++ header, and C ++ header contains other C header files ++).

There are two ways to resolve this issue:

  • Use a preprocessor to conditionally include C ++ headers only when compiling in C ++. This can be done, for example,

    #ifdef __cplusplus
    # include some_cpp_header
    #endif
    
  • ++ ( ) . , , C, ( extern "C" ++) API. :

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

.

+5

<iostream>, -compiler.

+1

All Articles