Using dllimport in place of dllexport

走远了吗. 提交于 2020-03-16 08:09:22

问题


I seem to be able to use __declspec(dllexport) and __declspec(dllimport) interchangeably when building my dll in Visual Studio 2015. I would have thought when making the DLL that the dllexport command would have been required but it seems either dllexport or dllimport is adequate.I have the following header file declaring a simple add() functions:

add.h

#pragma once

#ifdef ADDDLL_EXPORTS
#define ADDDLL_API __declspec(dllexport)
#else
#define ADDDLL_API __declspec(dllimport)
#endif

ADDDLL_API int add(int x, int y);

with the following definition in a cpp file:

add.cpp

#include "add.h"

int add(int x, int y)
{
    return x + y;
}

I seem to be able to use the built DLL whether ADDDLL_EXPORTS is defined or not in Configuration Properties > Preprocessor > Preprocessor Definitions. For example, in a separate project which includes the .lib file as an additional dependency (Configuration Properties > Linker > Input > Additional Dependencies), I have the following code that runs

main.cpp

#include <iostream>
#include "add.h"

int main()
{
    int sum = add(4, 5);
    std::cout << "sum = " << sum << std::endl;
    std::system("pause");
    return 0;
}

Any insight appreciated. Let me know if more information is needed. Thanks in advance!


回答1:


If you look carefully, you will see that your DLL project compiles with warnings, like this:

 c:\yourproject\add.cpp(3,1):warning C4273: 'add': inconsistent dll linkage

The compiler knows that you are up to no good. A dllimport function should not be defined, only declared. So when the compiler sees the definition, it assumes dllexport should be used instead, because that's the most reasonable resolution of the mistake.

It is a good practice to treat compiler warnings as errors.



来源:https://stackoverflow.com/questions/58138630/using-dllimport-in-place-of-dllexport

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