乐闻世界logo
搜索文章和话题

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

1个答案

1

In a Linux environment, building .so (shared object) files from .c source files using GCC (GNU Compiler Collection) typically involves several steps. These steps encompass both the compilation process and linking, along with ensuring appropriate configuration options. Below are the detailed steps and explanations:

Step 1: Writing Source Code

First, you need one or more C source files. Suppose we have a file named example.c with the following content:

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

Step 2: Compiling Source Files

To compile C source files into object files using the GCC compiler, you typically need to add the -fPIC (Position-Independent Code) option, which is necessary for shared libraries as it allows the code to execute correctly from any memory address.

bash
gcc -c -fPIC example.c -o example.o

The -c flag instructs GCC to compile only and generate the object file (example.o) without linking.

Step 3: Generating Shared Object .so Files

Next, use GCC to link the object file into a shared object file .so. The -shared option is required here.

bash
gcc -shared -o libexample.so example.o

This command creates a shared library file named libexample.so.

Example Explanation

In the provided example, we first compile the example.c file to generate the example.o object file. Then, we use this object file to generate the libexample.so shared library. This enables other C programs to link and utilize the hello function.

Using Shared Libraries

Other programs can utilize the hello function by specifying this shared library during linking, for example:

c
#include <stdio.h> extern void hello(); int main() { hello(); return 0; }

When compiling, you need to specify the linked library:

bash
gcc main.c -L. -lexample -o main

The -L. option directs the compiler to search for libraries in the current directory, and -lexample specifies linking to the libexample.so library.

By following these steps, you can create .so files from .c files and integrate them into other programs. This is the fundamental process for creating and using shared libraries in a Linux system.

2024年6月29日 12:07 回复

你的答案