C:创建静态库并使用Makefile进行链接 [英] C: Creating static library and linking using a Makefile

查看:480
本文介绍了C:创建静态库并使用Makefile进行链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解静态库和共享库.

我要执行以下操作来创建一个makefile,该makefile进行单独的编译和链接,以便创建并链接静态库 形成最终的静态可执行文件.

I want to do the following to create a makefile that does separate compilation and linking such that a static library is created and linked in forming the final static executable.

我的Makefile文件具有以下代码,但出现以下错误

I have the following code for the Makefile, but I am getting the following error

Makefile:13: *** missing separator. Stop.

但是我也试图了解如何实际链接/创建库.

But I am also trying to understand how to actually link/create libraries.

如果我在终端中的line 12之后运行命令,则它们会起作用,但不会在makefile中运行.

If I run the commands after line 12 in the terminal they work, but not in the makefile.

myProgram: main.o addSorted.o freeLinks.o
    gcc -lm -o myProgram main.o addSorted.o freeLinks.o

main.o: main.c
    gcc -O -c -lm main.c main.h

addSorted.o: addSorted.c addSorted.h
    gcc -O -c -lm addSorted.c

freeLinks.o: freeLinks.c freeLinks.h
    gcc -O -c -lm freeLinks.c

ar rc libmylib.a main.o addSorted.o freeLinks.o    //Error Line

ranlib libmylib.a

gcc -o foo -L. -lmylib foo.o

clean:
    rm -f myProgram main.o addSorted.o freeLinks.o

此外,如果您可以帮助改进代码,我将不胜感激.

Also, if you can assist in improving the code, I would really appreciate it.

推荐答案

尝试一下:

all: myProgram

myProgram: main.o libmylib.a #libmylib.a is the dependency for the executable
        gcc -lm -o myProgram main.o -L. -lmylib

main.o: main.c
        gcc -O -c main.c main.h

addSorted.o: addSorted.c addSorted.h
        gcc -O -c addSorted.c

freeLinks.o: freeLinks.c freeLinks.h
        gcc -O -c freeLinks.c

libmylib.a: addSorted.o freeLinks.o #let's link library files into a static library
        ar rcs libmylib.a addSorted.o freeLinks.o

libs: libmylib.a

clean:
        rm -f myProgram *.o *.a *.gch #This way is cleaner than your clean

这组规则首先编译所有文件,然后使库(libmylib.a)成为目标,并使用其工件链接可执行文件. 我还添加了单独的冗余目标表单,仅使libs成为可能. 所需文件:

This set of rules first compiles all files, then it makes library (libmylib.a) target and uses it's artifact to link the executable. I also added separate redundant target form making libs only. Needed files:

user@host> ls
addSorted.c  addSorted.h  freeLinks.c  freeLinks.h  main.c  main.h Makefile

这篇关于C:创建静态库并使用Makefile进行链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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