2

尝试使用 gcc 编译一个用 C 编写的简单 DLL。

尝试了许多教程,但即使我将文件剥离到最基本的内容,也无法编译它。

test_dll.c

#include <stdio.h>

__declspec(dllexport) int __stdcall hello() {
    printf ("Hello World!\n");
}

尝试使用命令编译它

gcc -c test_dll.c

失败,得到这个输出

test_dll.c: In function '__declspec':
test_dll.c:3:37: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'hello'
 __declspec(dllexport) int __stdcall hello() {
                                     ^
test_dll.c:5:1: error: expected '{' at end of input
 }
 ^

gcc 版本

gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
4

2 回答 2

5

这取决于您要执行的操作:

1.在linux上搭建linux库

然后删除__declspec(dllexport)and __stdcall。在 linux 上,构建库的源代码不需要什么特别的东西。请注意,库不是 linux 上的 DLL,它们被命名为*.so(共享对象)。您必须编译-fPIC并链接-shared才能创建.so文件。请使用谷歌了解更多详情。

2.在linux上构建windows DLL

安装 mingw 包(在你的包管理器中搜索它们)。然后,而不是仅仅gcc调用针对 windows/mingw 的交叉编译器,例如i686-w64-mingw32-gcc.

3.允许跨平台构建库,包括windows

如果您希望能够在 windows 和 linux 上使用相同的代码构建库,则需要一些预处理器魔法,因此__declespec()仅在针对 windows 时使用。我通常使用这样的东西:

#undef my___cdecl
#undef SOEXPORT
#undef SOLOCAL
#undef DECLEXPORT

#ifdef __cplusplus
#  define my___cdecl extern "C"
#else
#  define my___cdecl
#endif

#ifndef __GNUC__
#  define __attribute__(x)
#endif

#ifdef _WIN32
#  define SOEXPORT my___cdecl __declspec(dllexport)
#  define SOLOCAL
#else
#  define DECLEXPORT my___cdecl
#  if __GNUC__ >= 4
#    define SOEXPORT my___cdecl __attribute__((visibility("default")))
#    define SOLOCAL __attribute__((visibility("hidden")))
#  else
#    define SOEXPORT my___cdecl
#    define SOLOCAL
#  endif
#endif

#ifdef _WIN32
#  undef DECLEXPORT
#  ifdef BUILDING_MYLIB
#    define DECLEXPORT __declspec(dllexport)
#  else
#    ifdef MYLIB_STATIC
#      define DECLEXPORT my___cdecl
#    else
#      define DECLEXPORT my___cdecl __declspec(dllimport)
#    endif
#  endif
#endif

然后DECLEXPORT在每个要由 lib 导出的声明和SOEXPORT每个定义的前面放置一个。这只是一个简单的例子。

于 2017-05-11T15:10:50.317 回答
2

由于您是在 Linux 上编译,因此gcc将 Linux 作为目标。

您要做的是为 Windows 进行交叉编译。这意味着您将需要一个交叉编译器。可用于 Ubuntu Linux 的是 mingw。

您可以使用安装它

apt-get install gcc-mingw32 

然后你可以编译

gcc-mingw32 -c test_dll.c

需要进一步编译成 dll

gcc-mingw32 --shared test_dll.o -o test_dll.dll

然后可以在 Windows 上使用此 dll。

于 2017-05-11T15:11:56.043 回答