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

the*_*edi 1 c++ windows codeblocks

我创建了一个名为 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码来自我在网上找到的一个我可以理解的示例。当我尝试编译和/或构建它时,我收到以下错误和警告:

error: function 'void print()' definition is marked dllimport
In function 'void print()':
warning: 'void print()' redeclared without dllimport attribute: previous dllimport ignored
Run Code Online (Sandbox Code Playgroud)

这是我创建的第二个库,因为当发生这种情况时,我试图复制第一个库中的问题。怎么了?我正在使用代码::块。

Dav*_*nan 5

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

#define BUILD_DLL
#include "main.h"
Run Code Online (Sandbox Code Playgroud)

在您的程序中,您可以声明printwith ,因为在未定义__declspec(dllimport)时会处理头文件。BUILD_DLL