[code小心得] 編譯靜態檔 動態連結檔 Makefile等相關範例

大家好  小弟又來嘴炮了   今天大概舉一下相關編譯的範例  搭配Makefile
 當然也可以使用 指令的方式來編譯    故中的差異  就請各自體會囉

 順便給自己做個紀錄一下
不然真的好容易忘掉

忘了補充 靜態檔 可用 指令 ar 來生成

 ex:  ar -rv  libtest_d.a  getarg.o  write.o

另外查看有哪些.o檔的方式可以用

ex:  ar  -t  libtest_d.a

另外還有一些好工具  readelf 等 ,歡迎大家各自去man 一下

main.c #include #include #include #include "getarg.h" #include "writeinfo.h" const char ro_data[1024] = {"Readonly Data"}; static char rw_data[1024] = {"ReadWrite Data"}; static char bss_data[1024]; int main(int argc, char * argv[]) { int sum; printf("===main begin===\n"); //call getarg getarg(argc,argv); //call writeinfo sum = writeinfo(argv[0], 1234); printf("write sum:%d\n", sum); strcpy(bss_data, "BSS Data"); printf("ro_data:%x,%s\n", (unsigned int)ro_data,ro_data); printf("rw_data:%x,%s\n", (unsigned int)rw_data,rw_data); printf("bss_data:%x,%s\n", (unsigned int)bss_data,bss_data); printf("===main end===\n"); return 1; } writeinfo.h #ifndef __WRITEINFO_H__ #define __WRITEINFO_H__ int writeinfo(const char * string,int number); #endif writeinfo.c #include #include #include "writeinfo.h" #define FILENAME "logfile.txt" static const char info[] = {"writw information to file..."}; int writeinfo(const char * string,int number) { FILE * file; char writestring[1024]; int sum = 0; file = fopen(FILENAME, "wb"); if(file == NULL){ return -1; } sprintf(writestring,"%s\nstring:%s,number:%d\n", info, string, number); sum = fwrite(writestring, 1, strlen(writestring), file); fclose(file); return sum; } getarg.h #ifndef __GETARG_H__ #define __GETARG_H__ int getarg(int argc,char * argv[]); #endif getarg.c #include #include "getarg.h" int getarg(int argc,char * argv[]) { int i; printf("get argument list\n"); for(i=0;i Makefile CC := gcc HEAD := getarg.h SRC := getarg.c writeinfo.o main.c OBJS := getarg.o writeinfo.o main.o TT := test Files := $(wildcard ./*) INC = . CFLAGS = -pipe -g -Wall -I$(INC) LDFLAGS = -Wall -g all:$(TT) $(TT):$(OBJS) @echo "+++ Build Standalone Programe : $@ +++" $(CC) $(LDFLAGS) $(OBJS) -o $@ libtest_d.so:getarg.o writeinfo.o @echo "+++ Build Dynamic lib : $@ +++" $(CC) -shared $(LDFLAGS) getarg.o writeinfo.o -o $@ test_dlib:libtest_d.so main.o @echo "+++ Build Exe by Dynamic lib : $@ +++" $(CC) $(LDFLAGS) main.o -L. -ltest_d -o $@ filelist: @echo "<<< File in this folder>>>" @file $(Files) .PHONY : clean filelist %.o:%c $(CC) $(CFLAGS) -c $< -o $@ clean: @echo "----- clean -----" rm -f *.o rm -f $(TT) rm -f libtest_d.so rm -f test_dlib 以上就先這樣囉 感謝 下台一鞠躬

留言