Linux 使用 gcc 命令行从 .c 文件构建 .so 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14884126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:01:04  来源:igfitidea点击:

Build .so file from .c file using gcc command line

clinuxgccshared-libraries

提问by sashoalm

I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c:

我正在尝试为 Linux 动态库(.so 文件)创建一个 hello world 项目。所以我有一个文件hello.c:

#include <stdio.h>
void hello()
{
    printf("Hello world!\n");
}

How do I create a .so file that exports hello(), using gcc from the command line?

如何hello()从命令行使用 gcc创建一个导出的 .so 文件?

采纳答案by dreamcrash

To generate a shared library you need first to compile your C code with the -fPIC(position independent code) flag.

要生成共享库,您首先需要使用-fPIC(位置无关代码)标志编译 C 代码。

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

这将生成一个目标文件 (.o),现在您使用它并创建 .so 文件:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

编辑:来自评论的建议:

You can use

您可以使用

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

一步完成。—乔纳森·莱夫勒

I also suggest to add -Wallto get all warnings, and -gto get debugging information, to your gcccommands. – Basile Starynkevitch

我还建议在您的命令中添加-Wall以获取所有警告并-g获取调试信息gcc。——巴西尔·斯塔林克维奇