C And C++ Coding Standards

后端 未结 6 1986
不思量自难忘°
不思量自难忘° 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:47

    There are no good hard and fast rules here.

    If the end product will always be linked with a C++ main() then it does not really matter. As you can always create headers that will do the correct thing.

    If you are creating a library that needs to have a C and C++ interface but you can't assume the C++ linker then you will need to make sure you separated the C API from the C++ cleanly. At this point it is usually cleaner to do all the work in C and use C++ classes to proxy to the C.

    For example:

    /* c header */
    
    struct CData
     { /* stuff */ };
    
    void init( CData* data );
    void fini( CData* data );
    int getSomething( CData* data );
    void doSomething( CData* data, int val );
    
    // c++ header
    
    extern "C" {
    #include cdata.h
    };
    
    class CppData : private CData
     {
     public:
       CppData() { ::init( (CData*)this ); }
       ~CppData() { ::fini( (CData*)this ); }
       int getSomething() { return ::getSomething( (CData*)this ); }
       void doSomething( int val ) { :: doSomething( (CData*)this, val ); }
     };
    

    I hope this helps.

提交回复
热议问题