c++ - 简单的 DLL 给我奇怪的编译错误

标签 c++ winapi dll compilation

我正在创建我的第一个 DLL。我只有一个单例类和一个 LRESULT CALLBACK 函数,我将在 DLL 中创建它并将其导入到我的一个项目中。我的 MSVC++ 项目架构由 DLLMain.cpp 文件(未更改)、一个定义单例类和 LRESULT 函数的头文件以及一个实现 LRESULT 函数的 cpp 文件组成。

我的问题:项目没有编译。我有 2 个编译错误,我不明白究竟是什么错误以及如何修复它。

1>c:\users\testcreatedll\dlltest.h(15): error C2059: syntax error : '__declspec(dllexport)'
1>c:\users\testcreatedll\dlltest.h(39): error C2065: 'TestWndProc' : undeclared identifier

我的头文件:

#ifndef DLLTEST_H
#define DLLTEST_H

#include <windows.h>

// This is from a tutorial I am following
#ifdef _CLASSINDLL
#define CLASSINDLL_CLASS_DECL __declspec(dllexport)
#else
#define CLASSINDLL_CLASS_DECL __declspec(dllimport)
#endif

namespace MyTest
{
    LRESULT CALLBACK CLASSINDLL_CLASS_DECL TestWndProc( HWND hwnd, UINT msg, LPARAM lParam, WPARAM wParam );

    class CLASSINDLL_CLASS_DECL TestClass
    {
        // Singleton class
        public:
            static bool testStaticVar;

            static TestClass* getInstance()
            {
                if ( instance == NULL ) { instance = new TestClass(); }
                return instance;
            }

            void add()
            {
                myMember++;
            }

        private:
            static TestClass* instance;
            WNDPROC myProc;
            int myMember;

            TestClass() : myMember(0) { myProc = (WNDPROC)&TestWndProc; }
            ~TestClass()              {}

    };
}

#endif // DLLTEST_H

我的cpp文件:

#include "stdafx.h"
#include "DLLTest.h"

namespace MyTest
{
    // Create/Initialise? Class Static variables
    bool TestClass::testStaticVar = false;
    TestClass* TestClass::instance = NULL;

    LRESULT CALLBACK TestWndProc( HWND hwnd, UINT msg, LPARAM lParam, WPARAM wParam )
    {
        switch (msg)
        {
            case WM_CREATE:
            {

            }
            break;
            default:
            break;
        }

        return DefWindowProc(hwnd, msg, wParam, lParam);
    }

}

最佳答案

C++ 编译器可能非常对您声明调用约定和存储类信息(使用 __declspec 可见地导出)的顺序挑剔。 AFAIK,VC++ 需要调用约定出现在存储类之后。例如:

namespace MyTest
{
  LRESULT CLASSINDLL_CLASS_DECL CALLBACK TestWndProc( HWND hwnd, UINT msg, LPARAM lParam, WPARAM wParam );

  // ...
}

另一方面,C++ Builder 2007 和 MinGW-GCC-4.5.2 并不关心这个——两种形式都被接受。

关于c++ - 简单的 DLL 给我奇怪的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055077/

相关文章:

c++ - boolean 变量没有初始化就有值?

c++ - 在当前进程中 Hook API 调用?

c++ - 如何将库静态链接到 DLL?

c++ - 链接共享库的依赖项

c++ - OpenCV/C++ - 经过一些图像处理后将灰度图片转换为 BGR 图片

c++ - std::sort 对于少量数据来说很慢

c++ - 将直接值传递给 CreateIoCompletionPort() 的 CompletionKey 参数

c# - 创建 C# 应用程序以配置打印机页面设置

dll - 我们可以在一个进程中加载​​ 2 个同名的 DLL

powershell - 如何从 DLL 导入 Cmdlet