link static lib failed: undefined reference

cc -L. -lutil main.o -o prog

this line does not work

cc main.o -L. -lutil -o prog

this would work. because the arguments' sequence is important, always put the definition behind, or you will got previos issue.

for example, first compile and archive "prstc.c" to "libprstc.a", then you want to compile and link "prstc_test.c", because "func" is called by "main", so "-lprstc" should be put behind "prstc_test.c", like this:

# build.sh

set -x
cc -c prstc.c -o prstc.o
cc -c prstc_test.c -o prstc_test.o
ar rc libprstc.a prstc.o
ranlib libprstc.a
cc prstc_test.o -L. -lprstc -o prstc_test
./prstc_test

// prstc_test.c

#include "prstc.h"
void main(){
    func();
}

// prstc.h

#ifndef prstc_h
#define prstc_h
void func();
#endif
// prstc.c

#include"prstc.h"
#include<stdio.h>
void func(){
    printf("static lib test!\n");
}


你可能感兴趣的:(link static lib failed: undefined reference)