Search code examples
c++cmultiple-languages

To what extent is it permissible to combine C and C++?


I'm writing a chat server for class. I'd like to use C's network protocols, but I'm more comfortable programming in C++, particularly in terms of string manipulation.

As I understand it, you can combine the two in a single file and compile for C++ and it'll still accept the C code so long as the proper #include's are there.

What are the limitations on this? What should I look out for? Is there anything in particular from C that will not work in a .cpp file?


Solution

  • You should be able to #include and use standard headers including the networking headers in C++ without doing anything special.

    There are some differences between C and C++, but its unlikely you'll run into any problems because of it.

    One difference is enums. In C, an enum is just an int. In C++, an enum is an actual type. This code is valid C, but invalid C++.

    enum sport {
        hockey,
        baseball,
        soccer,
        vollyball
    };
    
    enum sport s = 5;
    

    Compiling this with g++ gives

    test.c:11: error: invalid conversion from ‘int’ to ‘sport’

    Here is more information on mixing C and C++.