C: Creating static library and linking using a Makefile

前端 未结 2 997
长情又很酷
长情又很酷 2020-12-08 16:03

I am trying to understand static and shared Libraries.

I want to do the following to create a makefile that does separate compilation and linking such that a static

2条回答
  •  死守一世寂寞
    2020-12-08 16:42

    Try this:

    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
    

    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
    

提交回复
热议问题