gpt4 book ai didi

c - 尝试使用 gcc 编译用 C 编写的简单 dll 失败

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:21 24 4
gpt4 key购买 nike

尝试使用 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 version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)

最佳答案

这取决于你想做什么:

1。在 linux 上为 linux 构建一个库

然后删除 __declspec(dllexport)__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,在每个定义前放置一个SOEXPORT。这只是一个简单的例子。

关于c - 尝试使用 gcc 编译用 C 编写的简单 dll 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com