C And C++ Coding Standards

后端 未结 6 1987
不思量自难忘°
不思量自难忘° 2021-01-18 00:00

What are best practices with regards to C and C++ coding standards? Should developers be allowed to willy-nilly mix them together. Are there any complications when linking

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 00:56

    The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having "C" linkage using extern "C". You can do this in the header file directly using:

    #if defined( __cplusplus )
    extern "C" {
    #endif
    
    extern int myfunc( const char *param, int another_one );
    
    #if defined( __cplusplus )
    }
    #endif
    

    You need the #ifs because C code that includes it won't understand extern "C".

    If you don't want to (or can't) change the header file, you can do it in the C++ code:

    extern "C" {
    #include "myfuncheader.h"
    }
    

    You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes.

    Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.

提交回复
热议问题