MinGW中的静态链接库 [英] Statically linking libraries in MinGW

查看:599
本文介绍了MinGW中的静态链接库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个C源文件.前两个是LIB(lib * .a?),第三个是使用它们的应用程序.

Suppose I have three C source files. The first two to be LIBs (lib*.a?), and the third is an application which uses them.

第一个是(re.c):

The first is (re.c):

int re(int i) {
    return i;
}

第二个是(test.c):

The second is (test.c):

int re(int); // Depends on re.c

int test(int i) {
    return re(i);
}

第三个是(main.c):

And the third is (main.c):

#include<stdio.h>

int test(int); // Uses test.c

int main(void) {

    printf("%d\n",test(0));
    return 0;
}

现在如何创建前两个LIB,使我以后可以将它们与主应用程序静态链接?

Now how can I create the first two LIBs in such a way that allows me to statically link them later with main application?

我知道如何创建DLL并将其动态链接到我的应用程序中,例如:

I know how to create the DLLs and link them dynamically in my application such as:

cc -o re.dll re.c -shared -Wl,-out-implib = libre.a(for re.c)

cc -o re.dll re.c -shared -Wl,--out-implib=libre.a (for re.c)

cc -o test.dll test.c -L. -lre -shared -Wl,-out-implib = libtest.a(用于test.c)

cc -o test.dll test.c -L. -lre -shared -Wl,--out-implib=libtest.a (for test.c)

cc -o main.exe main.c -L. -lre -ltest

cc -o main.exe main.c -L. -lre -ltest


那么,如何在MinGW的可执行二进制文件中创建等效的LIB进行静态链接,以及如何链接它们?


So how to create equivalent LIBs to be statically linked within my executable binary in MinGW, and how to link them?

很明显,在Windows下:)

Obviously, under Windows :)

推荐答案

我在这里找到了解决方案:

I found the solution here: http://www.codeproject.com/Articles/84461/MinGW-Static-and-Dynamic-Libraries

想法是编译所有库(源文件)而不链接.然后使用ar rcs -o lib*.a *.o转换输出对象,其中*是创建的对象的名称(一一转换).之后,我们只需使用-L.编译应用程序以指定目录,并使用-l*编译应用程序以指定没有GNU命名修饰的库名称.

The idea being is to compile all libraries (source files) without linking. Then converting the output objects with ar rcs -o lib*.a *.o where * is the name of objects created (converting them one by one). After that, we simply compile the application with -L. to specify the directory and with -l* to specify libraries names without GNU naming decoration.

对于那些依赖于其他库的库,应该先指定它们,然后再引用库,否则当我执行-lre -ltest时会出现诸如undefined reference to re之类的错误,其中-ltest -lre是正确的,因为测试库是指重新库.

For those libs which depends on others, they should be specified first and then the referenced libs, or else errors such as undefined reference to re will occur when I did -lre -ltest, where -ltest -lre is the right one, because test library refers to re library.

这是我的编译方式:

cc -c -o test.o re.c

cc -c -o test.o re.c

cc -c -o re.o re.c

cc -c -o re.o re.c

ar rcs -o libtest.a test.o

ar rcs -o libtest.a test.o

ar rcs -o libre.a re.o

ar rcs -o libre.a re.o

cc -o main.exe main.c -L. -ltest -lre

cc -o main.exe main.c -L. -ltest -lre

它也适用于Tiny C编译器.

It also works for Tiny C Compiler.

这篇关于MinGW中的静态链接库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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