Search code examples
c++cheader-files

How to use C code in C++


Just a small question: Can C++ use C header files in a program?

This might be a weird question, basically I need to use the source code from other program (made in C language) in a C++ one. Is there any difference between both header files in general? Maybe if I change some libraries... I hope you can help me.


Solution

  • Yes, you can include C headers in C++ code. It's normal to add this:

    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
    // C header here
    
    #ifdef __cplusplus
    }
    #endif
    

    so that the C++ compiler knows that function declarations etc. should be treated as C and not C++.