How does C's “extern” work?

后端 未结 7 1468
轻奢々
轻奢々 2020-12-28 10:56

I have a C/C++ program that\'s a plugin to Firefox. Because it\'s a plugin, it has non-main entry points. Those entrypoints need to be compiled in C because otherwise they g

相关标签:
7条回答
  • 2020-12-28 11:45

    The least confusing thing (at least for me) to do is to make the declarations in the header match the function definitions. As other answers have mentioned, it's the declaration/prototype that matters most - the extern "C" linkage specification can be omitted from the function definition as long as the prototype has been 'seen' by the compiler already when it gets to the definition. However, personally I find it preferable and less potentially confusing to have the declarations and the definitions match, but that's a preference that other programmers might not share.

    Note that you don't have to extern "C" everything in a header or implementation file - the extern "C" can be applied to a single name or to a group of names (by applying it to a block).

    So, in your header you can have something like:

    // entrypoints.h
    
    #ifdef __cplusplus
    // this opens an extern "C" block, but only if being included for a C++ compile
    //  if this is being included in a C compile, the extern "C" bits won't be seen
    extern "C" {
    #endif
    
    int foo(void);
    int bar( void*);
    
    
    #ifdef __cplusplus
    // close the extern "C" block, but only if we started it in the first place
    }
    #endif
    

    And your implementation of them:

    // entrypoints.cpp
    
    // Note: since this is a .cpp file, it's compiled as C++ so we
    //  don't need the #ifdefs around the extern "C"
    
    #include "entrypoints.h"
    
    extern "C"
    int foo(void)
    {
        return 42;
    }
    
    
    extern "C"
    int bar( void* p)
    {
        return -42;
    }
    
    0 讨论(0)
提交回复
热议问题