DLL 中的函数被错误地标记为 dllimport

Function in DLL is incorrectly marked dllimport

我创建了一个名为 Test Lib 的 DLL 项目:

// main.h
#ifndef __MAIN_H__
#define __MAIN_H__

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

extern "C" {
    DLL_EXPORT void print();
}
#endif

// main.cpp
#include "main.h"
#include <iostream>

#define BUILD_DLL

using std::cout;
using std::endl;

extern "C" {
    DLL_EXPORT void print() {
        cout << "Success" << endl;

        return;
    }
}

以上代码是根据我在网上找到的一个我能理解的例子。当我尝试编译 and/or 构建它时,出现以下错误和警告:

error: function 'void print()' definition is marked dllimport
In function 'void print()':
warning: 'void print()' redeclared without dllimport attribute: previous dllimport ignored

这是我创建的第二个库,因为我试图在第一个库中重现这个问题。怎么了?我正在使用 Code::Blocks.

在包含头文件main.h之前,您需要定义BUILD_DLL

#define BUILD_DLL
#include "main.h"

在您的程序中,您将 print 声明为 __declspec(dllimport),因为头文件是在未定义 BUILD_DLL 时处理的。