Is there a way to suppress c++ name mangling?

扶醉桌前 提交于 2019-12-18 04:25:09

问题


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.


回答1:


"bradtgmurray" is right, but for Visual C++ compilers, you need to explicitly 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 functions 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 ;
}

} ;



回答2:


Surround the function definitions with extern "C" {}

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

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




回答3:


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.



来源:https://stackoverflow.com/questions/902468/is-there-a-way-to-suppress-c-name-mangling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!