1)获取当前目录下的所有的目标。o文件,并把所有目标文件汇编出结果
objects := $(patsubst %.c,%.o,$(wildcard *.c))
foo : $(objects)
cc -o demo $(objects)
2) notdir -- 除去文件全路径中的目录部分,patsubst -- 替换通配符
如:
src=$(wildcard *.c ./sub/*.c) -- 获取当前目录和当前sub目录下的所有.c文件
dir=$(notdir $(src)) -- 去掉所有.c文件中的路径部分,只剩下.c文件名
obj=$(patsubst %.c,%.o,$(dir) ) -- 把.c文件名用.o替换掉,获取所有的.o文件名
3)gcc 常用选项含义
-Wall -- 打开常见的警告信息(warning)
-O2 -- 开起二级优化
-std=c99 -- 指定源代码符合C99标准
-I -- 指定头文件寻找路径,如-I. -I/my/include
-c -- 只编译,不汇编,不连接
-o -- 指定输出文件
-L --指定链接器ld寻找链接库的目录如-L/my/lib
-l -- 指定链接器链接某个类库,如-lm表示链接libm.so,链接器先在标准库路径/usr/lib下面找libm.so,如果找不到,再到-L指定的路径去找。
3、制作和链接静态库的方法(Linux下):
《以下内容转自网络并有修改 -- http://hi.baidu.com/csudada/blog/item/418d55c54c1e1fa38226ac99.html》
# 静态库名字约定为:libxxxx.a xxxx为文件的名字,a为静态库的后缀
1:建静态库
/* hellos.h */
#ifndef _HELLO_S_H
#define _HELLO_S_H
void printS(char* str);
#endif
/* hellos.c */
#include "hellos.h"
void printS(char* str) {
printf("print in static way: %s", str);
}
输入命令:
gcc -c -o hellos.o hellos.c
ar -rcqs libhellos.a hellos.o
[注:-rcqs]参数的含义为:
-r -- 替换已有或插入新的文件到.a库中去
-c -- 不打出警告信息,如果需要重新创建该库
-q -- 快速追加文件到库中去
-s -- 创建归档索引
于是得到了libhellos.a这么一个静态链接库
2:主程序
/* main.c */
#include "hellos.h"
main() {
char* text = "Hello World!\n";
printS(text);
}
编译链接:
gcc -o hello main.c -static -L. -lhellos
// L为指定静态库的路径参数,l为指定的静态库 此时只用引用xxxx就行,即:-lxxxx
然后运行hello可以看到输出
print in static way: Hello World!
删除libhellos.a和hellos.*后, 程序仍然正常运行。
4、创建动态链接库的方法(Linux下)
/* hellod.h */
#ifndef _HELLO_D_H
#define _HELLO_D_H
void printD(char* str);
#endif
/* hellod.c */
#include<stdio.h>
#include "hellod.h"
void printD(char* str) {
printf("print in dynamic way: %s", str);
}
输入命令:
gcc -shared -fpic -fPIC -o libhellod.so hellod.c
于是得到了libhellod.so这么一个动态链接库
注:-fpic 和-fPIC 最好和-shared一起使用
4:主程序
/* main.c */
#include "hellod.h"
main() {
char* text = "Hello World!\n";
printD(text);
}
编译gcc -c main.c得到main.o
链接:
gcc -o main.exe main.o -L. -lhellod
就可以得到main.exe,注意-lhellod 表示链接libhellod.so动态库.
然后运行./main.exe可以看到输出(注意,Linux下次是不一定能运行,提示找不到libhellod.so文件,这时需要把当前libhellod.so文件所在的目录加到LD_LIBRARY_PATH环境变量中,如 export LD_LIBRARY_PATH=./:${LD_LIBRARY_PATH})。