Question on DLL Exporting/Importing and Extern on Windows

前端 未结 2 1655
情歌与酒
情歌与酒 2021-01-18 14:57

I have some quick questions on windows dll.

Basically I am using the ifdefs to handle the dllexport and dllimport, my question is actually regarding the placement of

相关标签:
2条回答
  • 2021-01-18 15:36

    First, you don't need to import or export typedefs. As long as they're in the header files that both sides use, you're good. You do need to import/export functions and class definitions.

    Presumably you use the same header files for both the importing and exporting code, so you could do some makefile magic to define a preprocessor macro on each side, then do something like this:

    #if defined( LIBRARY_CODE )
    #define MYAPI __declspec(dllexport)
    #else
    #define MYAPI __declspec(dllimport)
    #endif
    
    extern MYAPI void func1();
    class MYAPI MyClass {
        ...
    };
    

    Regarding C vs. C++ functions, you can do this:

    #if defined( __cplusplus__ ) // always defined by C++ compilers, never by C
    #define _croutine "C"
    #else
    #define _croutine
    #endif
    
    extern _croutine void function_with_c_linkage();
    

    Make sure you import this header file from your C++ source file (containing the implementation of this function) or the compiler won't know to give it C linkage.

    0 讨论(0)
  • 2021-01-18 15:52
    1. typedefs do NOT need a dllimport/dllexport, it's just a definition
    2. dllimport/dllexport are not standard, think of defining a macro for other platforms/compilers
    3. also take care of the calling convention (cdecl,stdcall,...) used otherwise you'll run into problems (if you need to be interoperable with Visual basic use stdcall)
    4. enclose within extern "C" so that your lib can be used from within C++ programs, use #ifdef __cplusplus to keep it only visible to C++.

    Have a look at different OpenSource libs. There you'll find plenty of examples on how making a good library header. There could be issues with name decoration in the case of C++ without the extern "C".

    0 讨论(0)
提交回复
热议问题