MakeFile入门详解

记录第一篇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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小朋友的大哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值