记录第一篇Make File文件:有两个.c文件,thread.c中main函数,创建的线程函数在hello.c文件中,现编写hello.c和thread.c的MakeFile文件,将两者通过make来编译。
hello.c
#include <stdio.h>
#include <stdlib.h>
void* ptintf_hello_world(void* tid)
{
int arg = *(int *)tid;
printf("Hello world %d.\n", *(int *)tid);//在线程函数中打印函数的参数
int *a = (int *)malloc(sizeof(int));
*a = arg * arg;
return a;
}
thread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUMBER_OF_THREADS 10
extern void* ptintf_hello_world(void* tid);
int main(void)
{
pthread_t threads[NUMBER_OF_THREADS];
int status,i;
for(i=0;i<NUMBER_OF_THREADS;i++){//循环创建10个现场
printf("Main here. Creating thread %d\n",i);
//创建线程,线程函数传入参数为i
status=pthread_create(&threads[i], NULL, ptintf_hello_world, (void*)&i);
if(status!=0){//线程创建不成功,打印错误信息
printf("pthread_create returned error code %d\n",status);
exit(-1);
}
int **res = (int **)malloc(sizeof(int *));
pthread_join(threads[i], (void **)res);
printf("res[%d]:%d\n", i, **res);
free(*res);
}
exit(0);
}
根据上述两个.c的关系,MakeFile文件如下:
OBJS = hello.o thread.o
CC = gcc
CFLAGS = -Wall -O -g
thread:$(OBJS)
$(CC) $(OBJS) -o thread -lpthread
hello.o:hello.c
$(CC) $(CFLAGS) -c hello.c -o hello.o
thread.o:thread.c
$(CC) $(CFLAGS) -c thread.c -o thread.o
clean:
rm -rf *.o thread
CC指定编译器为gcc;
因为这里需要.o文件,但是这个文件会在下面指令生成,会自动先执行下面得到.o文件
gcc hello.o thread.o -o thread
此时.o文件还没有生成,依赖关系会自动生成
gcc -c hello.c -o hello.o
gcc -c thread.c -o thread.o
-c
是参数,编译和汇编,但不链接
-o
是指定输出文件,如果不指定,则会生成默认的文件名,比如a.out
,类似另存为操作。
中间过程的-E -s
省略了,内部完成了
使用make编译如下:
gcc -Wall -O -g -c hello.c -o hello.o
gcc -Wall -O -g -c thread.c -o thread.o
gcc hello.o thread.o -o thread -lpthread
make clean
rm -rf *.o thread