使用 mingw 遵循简单的 c++ DLL 教程时出错

Error following simple c++ DLL tutorial with mingw

我正在关注 https://cygwin.com/cygwin-ug-net/dll.html 的 "Building and Using DLLs" 教程。 我制作了 mydll.cpp 文件:

#include <iostream>

void hello()
{
    std::cout << "Hello World of DLL" << std::endl;
}

编译并链接它:

g++ -c mydll.cpp
g++ -shared -o mydll.dll mydll.o

然后尝试在 main.cpp 中使用 hello() 函数:

int main ()
{
  hello ();
}  

g++ -o main main.cpp -L./ -l mydll 链接后得到:

 error: 'hello' was not declared in this scope
 hello();

教程指出一切都应该正常。我错过了什么?

链接过程与编译过程是分开的。您提供的库包含链接过程中使用的 hello 的编译定义。

但是在链接之前发生的编译过程中,没有以任何方式使用这些库。为了让编译器知道 hello 是什么,您仍然需要声明该函数。

这通常是通过在 main.cppmydll.cpp 共享的头文件中放置前向声明来完成的。

// mydll.h

#ifndef HEADER_GUARD_MYDLL_H
#define HEADER_GUARD_MYDLL_H

void hello();

#endif

然后在 main.cppmydll.cpp#include "mydll.h"