1

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!

eball
  • 105
  • 5
  • Possible duplicate of [what does \_\_declspec(dllimport) really mean?](https://stackoverflow.com/questions/8863193/what-does-declspecdllimport-really-mean) – 500 - Internal Server Error Sep 27 '19 at 17:54
  • Thanks, I don't think this is a duplicate of the above post. I (believe) I understand what `dllimport` and `dllexport` are used for, but I'm not sure why I seem to be able to use them interchangeably because (I believe) they have opposite functions. – eball Sep 27 '19 at 18:09
  • 1
    You are able to *build* your DLL alright, are you able to *use* it? – n. m. could be an AI Sep 27 '19 at 18:30
  • @n.m., yes, I able to use it. I'll update my post to clarify this. – eball Sep 27 '19 at 18:36
  • What is the question here? – CristiFati Sep 29 '19 at 14:38
  • @CristiFati, sorry if it wasn't clear. The questions was why I can use `dllimport` in place of `dllexport`. n.m. was able to answer my question below. – eball Sep 30 '19 at 11:29

1 Answers1

3

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • You're right! Guess I need to learn to pay more attention to the output window haha. How do you know the compiler replaces `dllimport` with `dllexport`? Thanks! – eball Sep 30 '19 at 11:28