使用 gcc 命令行从 .c 文件构建 .so 文件 [英] Build .so file from .c file using gcc command line
问题描述
我正在尝试为 Linux 动态库(.so 文件)创建一个 hello world 项目.所以我有一个文件 hello.c:
I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c:
#include <stdio.h>
void hello()
{
printf("Hello world!
");
}
如何从命令行使用 gcc 创建导出 hello()
的 .so 文件?
How do I create a .so file that exports hello()
, using gcc from the command line?
推荐答案
要生成共享库,您首先需要使用 -fPIC
(位置无关代码)标志编译 C 代码.
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
这将生成一个目标文件 (.o),现在您使用它并创建 .so 文件:
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
编辑:来自评论的建议:
你可以使用
gcc -shared -o libhello.so -fPIC hello.c
一步完成.– 乔纳森·莱夫勒
我还建议在 gcc
命令中添加 -Wall
以获取所有警告,并添加 -g
以获取调试信息.– Basile Starynkevitch
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
这篇关于使用 gcc 命令行从 .c 文件构建 .so 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!