使用gcc命令行构建从.c文件.so文件 [英] Build .so file from .c file using gcc command line

查看:710
本文介绍了使用gcc命令行构建从.c文件.so文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建用于Linux动态库一个Hello World项目(.so文件)。所以我有一个文件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!\n");
}

如何创建一个.so文件出口你好(),用gcc在命令行?

推荐答案

要生成你需要先用编译C code共享库中的 -fPIC (位置无关code)标志。

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

做一步到位。 - 乔纳森·莱弗勒

我也建议添加 -Wall 来获取所有警告和 -g 来获取调试信息,以你的 GCC 命令。 - 巴西莱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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆