views:

785

answers:

3

I have a DLL that is written in C++ and I want to suppress the name mangling for a few exported methods. The methods are global and are not members of any class. Is there a way to achieve this?

BTW: I'm using VS2008.

+24  A: 

Surround the function definitions with extern "C" {}

extern "C" {
    void foo() {}
}

See http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

bradtgmurray
You need both the declaration and the definition to be extern "C"ed, right?
leander
+7  A: 

You can avoid all manglings (C++, cdecl, stdcall,...) for exported functions using a .def file with an EXPORTS section. Just create a MyDll.def file and add it to your project:

LIBRARY "MyDLL"
EXPORTS
  Foo
  Bar

Actually, chances are the wizard already created a def file for you. You just have to fill in the EXPORTS section.

Serge - appTranslator
+2  A: 

"bradtgmurray" is right, but for Visual C++ compilers, you need to explicitely export your function anyway. But using a .DEF file as proposed by "Serge - appTranslator" is the wrong way to do it.

What is the universal way to export symbols on Visual C++ ?

Using the declspec(dllexport/dllimport) instruction, which works for both C and C++ code, decorated or not (whereas, the .DEF is limited to C unless you want to decorate your code by hand).

So, the right way to export undecorated funtions in Visual C++ is combining the export "C" idiom, as answered by "bradtgmurray", and the dllimport/dllexport keyword.

An example ?

As an example, I created on Visual C++ an empty DLL project, and wrote two functions, one dubbed CPP because it was decorated, and the other C because it wasn't. The code is:

// Exported header
#ifdef MY_DLL_EXPORTS
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif

// Decorated function export : ?myCppFunction@@YAHF@Z
MY_DLL_API int myCppFunction(short v) ;

// Undecorated function export : myCFunction
extern "C"
{
MY_DLL_API int myCFunction(short v) ;
} ;

I guess you already know, but for completeness' sake, the MY_DLL_API macro is to be defined in the DLL makefile (i.e. the VCPROJ), but not by DLL users.

The C++ code is easy to write, but for completeness' sake, I'll write it below:

// Decorated function code
MY_DLL_API int myCppFunction(short v)
{
   return 42 * v ;
}

extern "C"
{

// Undecorated function code
MY_DLL_API int myCFunction(short v)
{
   return 42 * v ;
}

} ;
paercebal
Thanks for an awesome answer... exactly what I needed.
Polaris878