Linux學習入門--make學習總結

1.  make的做用

能夠根據模塊的修改狀況從新編譯連接目標代碼,保證目標代碼都是由最新的模塊組成的。html

2. makefile的編寫方法

  • 格式:

目標:依賴列表spa

    命令code

注意命令左側是Table製表位htm

  • 註釋

語句前加#表示註釋blog

  • @避免該行顯示,由於make默認是顯示執行過程的
  • \用來接續行比較長的狀況,與C語言相似
  • 變量的使用,變量通常用大小字母表示,格式: 變量名 = 字符串;引用方式 $(變量名)
  • ifeq(val1,val2), else, endif

舉個例子來講明字符串

gcc_hello_world.c
--------------------------------
#include <stdio.h>
#include "print.h"

int main(void)
{
 
  print_hello();

  return 0;
}


print.c
--------------------------------
#include <stdio.h>
#include "print.h"

void print_hello(void)
{
  printf("Hello world!\n");
}

print.h
---------------------------------
#ifndef PRINT_H
#define PRINT_H

void print_hello(void);

#endif

i. Makefile代碼:get

hello:gcc_hello_world.o print.o
	@gcc gcc_hello_world.o print.o -o hello
gcc_hello_world.o:gcc_hello_world.c print.h
	gcc -c gcc_hello_world.c
print.o:print.c print.h
	gcc -c print.c
	
clean:
	rm -f *.o hello

其中clean是僞目標,在make參數時能夠使用,執行結果以下:io

ii. 使用變量編寫Makefile編譯

OBJ=gcc_hello_world.o print.o

hello:$(OBJ)
	gcc $(OBJ) -o hello
gcc_hello_world.o:gcc_hello_world.c print.h
	gcc -c gcc_hello_world.c
print.o:print.c print.h
	gcc -c print.c
	
clean:
	$(RM) *.o hello

-------------------------------------------------------------------------------------------------------------class

明天繼續宏定義的實驗操做。

修改gcc_hello_world.c以下:

#include <stdio.h>
#include "print.h"

int main(void)
{
#ifdef MACRO  
  print_hello();
#endif
  return 0;
}
CC=gcc

CFLAGS += -DMACRO


TARGETS := hello

all:$(TARGETS)

OBJ=gcc_hello_world.o print.o

$(TARGETS):$(OBJ)
	$(CC) $(CFLAGS) $^ -o $@
	
gcc_hello_world.o:gcc_hello_world.c print.h
	gcc -c $(CFLAGS) gcc_hello_world.c
print.o:print.c print.h
	gcc -c print.c

clean:
	$(RM) *.o hello

:=     +=   ?= 參考文章:Makefile 中:= ?= += =的區別

$^ -o $@能夠參考makefile使用說明

其實添加宏定義方法和gcc -D的命令同樣。

相關文章
相關標籤/搜索