我有一个源文件 handleSSV.c
,我想编译它来创建一个自定义库。我该怎么做?
我在想:
gcc -o handle.h handleSSV.c
然后,
#include "handle.h"
什么时候我想使用handleSSV.c
?
最佳答案
它因平台而异,但头文件 (handleSSV.h
) 不会由 C 编译器生成;您将从源中的信息创建它。此命令序列是类 Unix 平台的“典型”命令。
gcc -c handleSSV.c # Generates handleSSV.o
ar r libhandleSSV.a handleSSV.o # Creates static library
gcc -o ssv-prog ssv-prog.c -L . -lhandleSSV # Creates program with library
如果你想建立一个共享库,那么你必须使用像这样的东西:
gcc -fPIC -o libhandleSSV.so -shared handleSSV.c
程序的链接行没有改变。请注意,.so
后缀被广泛使用但并未普遍使用(.sa
在较旧的 AIX 上;.shl
在较旧的 HP-UX 上;.dylib
在 Mac OS X 等上)。
Windows 上的规则相似,但在细节上有所不同。
演示
使用 GCC 4.8.2 在 Mac OS X 10.9.2 Mavericks 上运行的演示代码。
处理程序.h
#ifndef HANDLER_H_INCLUDED
#define HANDLER_H_INCLUDED
extern int handler(int a, int b);
#endif /* HANDLER_H_INCLUDED */
处理程序.c
#include "handler.h"
#include <stdio.h>
int handler(int a, int b)
{
int c = a + b;
printf("%d = %d + %d\n", c, a, b);
return c;
}
使用处理程序.c
#include "handler.h"
#include <stdio.h>
int main(void)
{
int d = handler(29, 31);
printf("d = %d\n", d);
return 0;
}
编译静态库和共享库等
$ gcc -c handler.c
$ ar r libhandler.a handler.o
ar: creating archive libhandler.a
$ gcc -o use-handler use-handler.c -L. -lhandler
$ ./use-handler
60 = 29 + 31
d = 60
$ gcc -o libhandler.dylib -shared -fPIC handler.c
$ gcc -o use-handler use-handler.c -L. -lhandler
$ otool -L use-handler
use-handler:
libhandler.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
/usr/gcc/v4.8.2/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
$ ./use-handler
60 = 29 + 31
d = 60
$
关于c - 如何编译C源文件来制作自定义库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824559/