【问题标题】:How to compile a static library in Linux?如何在 Linux 中编译静态库?
【发布时间】:2024-04-15 16:10:02
【问题描述】:

我有一个问题:如何在 Linux 中使用gcc 编译静态库,即我需要将我的源代码编译成一个名为 out.a 的文件。简单地使用命令gcc -o out.a out.c 编译就足够了吗?我对gcc不太熟悉,希望有人能帮帮我。

【问题讨论】:

标签: c gcc static-libraries


【解决方案1】:

Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c 表示创建中间对象文件,而不是可执行文件。

ar rcs libout.a out.o
 

这将创建静态库。 r 表示替换插入,c 表示创建新存档,s 表示写入索引。与往常一样,请参阅man page 了解更多信息。

【讨论】:

  • -o 不是必需的。输出将是相同的 (out.o)
【解决方案2】:

这里有一个完整的 makefile 示例:

制作文件

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

解释生成文件:

  • target: prerequisites - 规则负责人
  • $@ - 表示目标
  • $^ - 表示所有先决条件
  • $&lt; - 表示只是第一个先决条件
  • ar - 一个 Linux 工具,用于创建、修改和提取档案 see the man pages for further information。这种情况下的选项意味着:
    • r - 替换存档中现有的文件
    • c - 如果不存在则创建一个存档
    • s - 在存档中创建一个对象文件索引

总结:Linux下的静态库无非就是对象文件的存档。

ma​​in.c 使用库

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h lib 的主头文件

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c 第一个库源

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h 对应的头文件

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c 第二个库源

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h 对应的头文件

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

【讨论】:

  • 这将有助于指出命令的作用以及它们打算实现的目标。特别是在这种情况下,ar 需要解释,因为它是创建静态库的关键。
  • ar 程序创建、修改和从档案中提取,档案是单个文件,其结构中包含其他文件的集合,可以检索原始单个文件。当您指定修饰符 s 时,ar 为存档中可重定位对象模块中定义的符号创建索引。 (见man ar
  • 请在您的标题中添加以下行以支持c++ 编译器:#ifdef __cplusplus extern "C" { #endif . . . #ifdef __cplusplus } #endif
  • 这是一个绝妙的答案,谢谢!
【解决方案3】:

使用 gcc 生成目标文件,然后使用ar 将它们捆绑到静态库中。

【讨论】:

    最近更新 更多