Error C2491: definition of dllimport function not allowed

pawel112 picture pawel112 · Jun 7, 2016 · Viewed 15.8k times · Source

I have a problem with make a dll on Visual Studio 2013. This code works on Code::Blocks. The error was definition of dllimport function not allowed" on line void DLL_EXPORT prim(map<string, vector<int>> nodes, map<pair<string, string>, pair<int, string>> edges). How to fix it?

main.h:
#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>
#include <iostream>
#include <vector>
#include <map>

using namespace std;

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif


#ifdef __cplusplus
extern "C"
{
#endif

void DLL_EXPORT prim( map<string,vector<int>> nodes, map<pair<string,string>,pair<int,string>> edges);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__

And the second file:

main.cpp:
#include "main.h"
//some other includes

// a sample exported function

extern "C"
{
    void DLL_EXPORT prim(map<string, vector<int>> nodes, map<pair<string, string>, pair<int, string>> edges)
    {
        //some code
    }
}

I tried to fix it, but I have no more idea. When I changed the prim function in second file from definition to the declaration, the dll was compile without errors, but without the code responsible for the implementation of the algorithm.

Thanks for all replies.

Edit:

I add temporary #define BUILD_DLL to main.h and later in Cmake and I works. Thanks for replies.

Answer

sameerkn picture sameerkn · Jun 7, 2016

main.h and main.cpp will be used in DLL Project which you are creating.

only main.h will be used in client Executable/DLL which is accessing the DLL which you created.

So, main.h of DLL Project requires __declspec(dllexport). So that the functions can be exported from the DLL. So, define BUILD_DLL in DLL Project's Properties -> C/C++ -> 'Preprocessor definitions'

main.h of client Executable requires __declspec(dllimport). So that the functions can be imported from the DLL. So no need to define BUILD_DLL in Executable Project's Properties -> C/C++ -> 'Preprocessor definitions'