在C ++中调用静态链接的静态方法

时间:2015-05-24 16:43:27

标签: c++ winapi static-methods static-linking

我正在尝试调用C ++类的静态链接静态方法,但我得到VS链接器错误LNK2019,“未解析的外部符号”。这是图书馆的来源:

// in header file
#define DllExport __declspec (dllexport)
class MyClass{
public:
    DllExport
    static HWND WINAPI myFunc();
};
// in cpp file
DllExport
HWND WINAPI MyClass::myFunc(){ /* create a GUI window that has instance of MyClass set as its property (using ::SetProp) */ }

myFunc用作创建隐藏在库中的MyClass对象的入口点。只有这些静态函数可用于影响MyClass实例的功能(通过提供相应的HWND)。 这是图书馆消费者:

#define DllImport __declspec(dllimport)
DllImport
HWND WINAPI myFunc();
...
int main(){
    HWND hWnd=myFunc();
    ... // work with the window and attached MyClass instance
}

(我相信)所有文件链接都设置正确 - 最初,myFunc被设计为一个独立的功能,所有工作都很好。我怀疑它必须是一些调用会话不匹配,这会使链接器在myFunc上产生错误。 阅读有关该主题的多篇文章,即

http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL

https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx

但他们没有解决我的问题。

感谢您的建议!

2 个答案:

答案 0 :(得分:3)

Since your goal is to create static library, the first thing we want to do is eliminate any mention of dllexport/dllimport. Such specifiers are only used when you actually create a DLL project.

So for lib.h, we only need this (with some include guards added for good measure):

// lib.h
#ifndef LIB_H
#define LIB_H

class MyClass{
public:
    static void myFunc();
};

#endif

The WINAPI specification is also unnecessary since you're the one calling the method and can just use the default calling convention without ABI issues (though if you do want to use WINAPI anyway, then you need to include <windows.h> in your header file).

For lib.cpp, we only need this:

// lib.cpp
#include <Windows.h>
#include "lib.h"

void MyClass::myFunc(){
    ::MessageBox(0,"myFunc call!",NULL,0);
}

For main.cpp in your app project, we only need this:

// main.cpp
#include <iostream>
#include <D:\staticlink\lib\lib.h>

int main(){
    std::cout << "ahoj";
    MyClass::myFunc();
    char buf[10];
    std::cin >> buf;
    return 0;
}

I'd recommend configuring your include paths to find lib.h through your project settings instead of using absolute paths in your source code, but perhaps you can do that later after you get everything working.

After that, if a problem remains, the only thing you should need to ensure is that your app project is linking against lib.lib properly (linker settings).

答案 1 :(得分:1)

您的导入头文件应该更像:

#define DllApi __declspec (dllexport)
class MyClass{
public:
    DllApi
    static HWND WINAPI myFunc();
};