Search code examples
c++dlldllimportdllexportdeclspec

Using dllimport in place of dllexport


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!


Solution

  • 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.