Export C functions for use in C or C++ language executables

If you have functions in a DLL written in C, you can use a preprocessor macro to make them easy to access from both C language and C++ language code. The __cplusplus preprocessor macro indicates which language is being compiled. You may use it to declare the functions with C linkage when called from C++ language code. If you use this technique and provide header files for your DLL, these functions can be used by C and C++ users with no change.

The following code shows a header file that both C and C++ client applications can use:

// MyCFuncs.h
#ifdef __cplusplus
extern "C" {  // only need to export C interface if
              // used by C++ source code

__declspec( dllimport ) void MyCFunc();
__declspec( dllimport ) void AnotherCFunc();

#ifdef __cplusplus

Sometimes you may need to link C functions to your C++ executable, but the function declaration header files haven't used the above technique. You can still call the functions from C++. In the C++ source file, wrap the #include directive to prevent the compiler from decorating the C function names:

extern "C" {
#include "MyCHeader.h"

What do you want to do?

What do you want to know more about?

See also

Exporting from a DLL