[Linux] makefile multi-directory

Before writing the use of multi-directory makefile need to have several functions and symbols

Custom Variables

target=edit
When referenced directly$(target)

A bit like the C language #define, here $(target)will be replaced edit.

You can also replace multiple files, pay attention to space

object=main.o xxx.o xxx.o

Automatic variables

Automatic variables are used in the second row is gcc -c xxxin

$<: The first rule of a dependent
$@: Target rule
$^: Rule all depends

$(target):$(obj)
gcc \$^ -o \$@

This line means that the rules all the dependencies ($ ^) (. O files) to generate the target ($ @)

$(target)

Auto match

Sub rule:
目标:依赖

%.o:%.c
Rely on automatic matching of the ultimate goal:
main.o: main.c
add.o: add.c
sub.o: sub.c

makefile function

pro=$(wildcard src/*.c)
src=$(wildcard *.c)
obj=$(patsubst %.c,%.o,$(pro) $(src))

wildcardFind all .c files in the current directory and the src directory, and are returned to the pro src
pro=$(wildcard *.c)
src=$(wildcard src/*.c)
patsubstreplace all .c files to .o files
obj=$(patsubst %.c,%.o,$(pro) $(src))

Note:
I will be here with a space $(pro) $(src)separated, so at compile time system is not main.cxxx.cthe case, that is connected to the head and tail.

So, preparatory work is complete.

Code

.
├── main.c
├── makefile
└── src
    ├── Speak.c
    └── Speak.h

main.c

#include <stdio.h>
#include "src/Speak.h"
int main()
{
    printf("Helo\n");
    Speak();
    return 0;
}

src/Speak.c

#include "Speak.h"

void Speak(void)
{
printf("Speak\n");
}

src/Speak.h

#include <stdio.h>
void Speak(void);

Here began to explain the makefile

pro=$(wildcard *.c)
src=$(wildcard src/*.c)
obj=$(patsubst %.c,%.o,$(pro) $(src))

target=edit

$(target):$(obj)
    gcc $^ -o $@
%.o:%.c
    gcc -c $< -o $@

.PHONY:clean
clean:
    rm  $(obj) $(target) -f

We will root .c files in the directory (only one main.c) through a wildcardreturn to thepro

src.C files in the directory by wildcardthe return tosrc

By patsubstreplacing all .c files to .o files

By then rely on automatic matching

%.o:%.c
    gcc -c $< -o $@

.O files are generated every .c file

The final edit is generated executable file

$(target):$(obj)
    gcc $^ -o $@

sort out:

  1. Using the wildcardreturn .c files in each directory,

  2. The use of patsubstindividual .c into .o (This step does not generate .o file, only the equivalent of a main.creturn to main.o)

  3. The use of automatic matching to automatically generate various .o (this step is to generate .o file)
  4. All .o executable file edit

Guess you like

Origin www.cnblogs.com/cnleika/p/11422793.html