Shell scripts --make command and Makefile file [turn]

https://blog.csdn.net/twc829/article/details/72729799

make command is a command used to compile, in particular in C / C ++ development, make command automatically compile dependencies between source code described in the makefile;

the makefile is prepared in accordance with the prescribed format, for an explanation how to compile each source file and connected to generate an executable file, and requires the definition of the dependencies between source files;

The first time you run make command to compile all the relevant files, after re-execute the make command, incrementally compile that only the modified source files related to the target file to be compiled;

Note: Many tarball format of open source software, unzip first execution ./configure, then execute make, then run make install to install;

 

makefile file support include, that is dependent on a few basic rules to write in a public document, other makefile file contains this file;

Usually common makefile file named common.mk;

 

A, make command
make command, connection parameter, referred to as a target;

1 common goals
make all: Compile all targets

make install: install a compiled program

make uninstall: uninstall the installed program

make clean: delete the files generated by the make command and is usually deleted object files .o

make distclean: Delete files generated by ./configure

make check: just compiled software testing

Library and inspect the installation of: make installcheck

make dist: repackaged into packname-version.tar.gz

 

When the make command, you need a Makefile to tell how to make command to compile and link the program;

 

2 parameters
-B: to re-establish all targets

-d: print debug information

Looking Makefile switching to the specified path: -C

-f: seen as the specified file Makefile

-j: while the number of run command, i.e., the Makefile multithreaded execution, followed by the number of values ​​to specify the command returns nproc

Note: nproc command the number of prints (number of threads) currently available treatment process;

 

 

 

Second, compile and link the program
in general C / C ++ development, first of all the source files are compiled into object files (.obj files under Windows, Unix under .o file) - compiler compile, synthesize and then the target file executable file - link to link;

 

 

 

Third, how to make the command work?
1 make seeking "Makefile" or "makefile" file in the current directory

2 If found, find the file in the first object file .o

3 If the target file does not exist, according to find .s file dependencies

4 If the .s file does not exist, according to find .i file dependencies

If the file does not exist .i 5, .c file lookup according dependency, .c file must exist at this time, to thus generate a .o file, again performed

 

 

 

Four, the Makefile format
1 Overview
Makefile file consists of a series of rules rules, each rule in the form of the following:

<target>: <prerequisites>
[Tab]<commands>


The first line of the target before the colon, the colon is the precondition; second line must first of all by one key Tab, followed by the command;

Target is required, it can not be omitted; pre- and command is optional, but both must be present at least one;

Each rule clearly two things - what is the goal of building the pre-conditions? How to build?

 

2 goal target
destination can be a file name, specify the make command objects to be built; the name can also be an operation, called "pseudo-objective";

 

Clean:
RM * .o
above code object is clean, the command is rm * .o;

Execute the command make clean, delete achieve the object file;

 

To avoid false object name set with the same name of the file, make command to find the file name already exists in the current path, will no longer build, and not to perform rm operation happens, the name of the first statement is false target Therefore make command does not check the file name, each execution corresponding to the operation;

.PHONY:clean
clean:
rm *.o


If the make command does not specify a target, the default implementation of the Makefile the first goal;

 

3 prerequisites precondition
the pre-conditions are typically a set of file names, separated by a space;

Whether the reconstructed targeting criteria - as long as there is a pre-condition does not exist or is updated, the need to re-construct the target;

 

the result.txt: source.txt
CP source.txt the result.txt
If the current path source.txt presence, make result.txt be executed normally, or need to write a rule for generating source.txt;

 

the Source.txt:
echo. "This IS A Source File"> the Source.txt
the Source.txt no preconditions other civil documents, as long as the file does not exist, each execution of the command will make source.txt generate the file;

 

To generate multiple files, worded as follows:

source:file1 file2 file3


source is the pseudo target, only three pre-conditions, there is no corresponding command; generating a file file1 file2 file3 disposable after executing the make command source, such as to facilitate the wording:

make file1
make file2
make file3


4 Command commands
command shows how to update the target file, the command shell composed of one or more lines;

Note:

shell commands must be written in command, otherwise it will be make ignored;

There must be a Tab key before each command;

Each command in a separate shell is executed, there is no inheritance relationship between the shell, and therefore variable assignment on a behavior, the next line is invalid;

If the command is shared data before and after the two, may be on one line, separated by a semicolon;

var-kept:
export foo=bar;echo "foo=[$$foo]"


Or before newline with a backslash \ escape;

var-kept:
export foo=bar;\
echo "foo=[$$foo]"


Or, together with .ONSHELL command;

.ONESHELL:
var-kept:
export foo=bar;
echo "foo=[$$foo]"

 

 


Five, Makefile file syntax
1 comment
each line beginning with # is a comment;

 

2 echo echoing
Under normal circumstances, make prints each command, and then execute the command, said echo;

Command Adding @ echo off, i.e. only the output execution result of the command, an error stops the execution;

Note:

Prefix - represents the command execution is wrong, ignore the error and continue execution;

Command prefix is ​​not performed and the output of the results of command execution, error stops the execution;

 

3 wildcards
wildcards to specify a set of qualifying documents;

Makefile wildcard consistent with bash;

*: Any zero or more characters

?: Any one character

[...]: any character within square brackets

 

4 pattern matching
make command allows a similar file name that matches the regular operation, mainly used%;

 

5 and variable assignment operator
custom variables, using the = assignment;

Call variable, the variable name on the $ () in;

Makefile offers four assignment operator - =,: =, =, + =;?

(1)=

Recursively expand assignment, the default assignment mode;

= $ var2 (var1)
var1 = "the TEST"
All:
echo $ (var2)
Output: TEST

 

(2):=

Direct assignment, will not populate the child, if there is no variable references, or an empty string;

var2: = $ (var1)
var1 = "the TEST"
All:
echo $ (var2)
output :( empty string)

 

(3)?=

If not initialized, then the assignment;

var1="test"
var1?="TEST"
var2?="TEST"
all:
<span> </span>echo $(var1) and $(var2)
输出:test and TEST

 

(4)+=

Appended to the existing value of the end of the content;

var1="TEST"
var1+="test"
all:
<span> </span>echo var1
输出:TESTtest

 

 

 

Six built-in variables
make command provides a range of built-in variables, such as $ (CC) points to the compiler currently in use, $ (MAKE) point to make tools currently in use;

RM: rm -f

ON: on

CC: cc

CXX:g++

 

 

 

Seven automatic variable
value is automatically variable with the current rules;

1 $@

It indicates the current target;

 

2 $<

It represents a precondition;

 

3 $?

Means that all pre-conditions newer than the target;

 

4 $^

Means that all pre-conditions;

 

5 $ (@ D) and $ (@ F)

$ (@ D) represented $ @ target name, $ (@ F) indicates the file name of the $ @;

 

 

 

Eight, to determine
the Makefile using bash syntax completion judgment;

<Conditional statements>
<condition is true, execution block>
the else
<condition is false, execution block>
endif


1 conditional statement

(1) ifeq compare two parameter values ​​are equal

ifeq (arg1, arg2)

ifeq 'arg1' 'arg2'

ifeq "arg1" "arg2"

ifeq 'arg1' "arg2"

ifeq "arg1" 'arg2'

NOTE: The parameter may also make use function, such as ifeq ($ (strip $ (foo)),);

 

(2) ifneq compare two parameter values ​​are unequal

ifneq (arg1, arg2)

ifneq 'arg1' 'arg2'

ifneq "arg1" "arg2"

ifneq 'arg1' "arg2"

ifneq "arg1" 'arg2'

 

If (3) ifdef whether the variable has the value

ifdef var

 

(4) ifndef determines whether or not the value of variable

ifndef was

 

Example 1:

bar=
foo=$(bar)
ifdef foo
frobozz=yes
else
frobozz=no
endif
#frobozz值为yes


Example 2:

= foo
ifdef foo
frobozz Yes =
the else
frobozz = no
endif
#frobozz value no
Note: The above exemplified ifdef only tests whether there is a variable value, instead of the current position to the extended variable!

 

 

 

Nine, recycling
Makefile file using bash syntax completion judgment;

Writing a 1
LIST Makefile variable is a variable, the variable reference Makefile need to use $ () enclosed;

And after all is the goal of the command shell command, which defines the variables are shell variables shell variable need to use $$ cited as the beginning, but the shell variable without parentheses;

LIST = one two three
all:
for i in $(LIST); do \
echo $$i; \
done


2 写法二
all:
for i in one two three; do \
echo $$i; \
done

 

 


Ten, the function
call syntax 1 function
function call, similar variables, the syntax is as follows:

$ (func args) # recommendation!
# Or
$ {func args}
wherein, between args parameter "," to "" between spaced apart, func and args;

 

2 string handling functions
(1) $ (subst <from >, <to>, <text>)

Alternatively the string, the string <text> in the <from> converted to <to>, the replacement string is returned;

 

(2)$(patsubst <pattern>,<replacement>,<text>)

Alternatively pattern string, the search string <text> patterns that match <pattern> word, and replaced with <replacement>;

NOTE: <pattern> may include wildcard%, represents an arbitrary length string;

If <replacement>% also includes, where% is the string <pattern> represented in%;

 

(3)$(strip <string>)

Space to remove <string> leading and trailing whitespace, remove spaces returns a string;

 

(4)$(findstring <find>,<in>)

Find string Find <find> string in the string <in>, if the find is returned <find>, otherwise it returns an empty string;

 

(5)$(filter <pattern...>,<text>)

Filtered, and filtered to <pattern> Mode <text> string of words, a word matching the patterns are retained, returns a string matching the patterns;

There may be a plurality of modes, the "" between a spaced apart mode;

 

(6)$(filter-out <pattern...>,<text>)

Inverse filtering, and filtered to <pattern> Mode <text> string of words, a word matching the patterns are removed, returns the string does not conform mode;

There may be a plurality of modes, the "" between a spaced apart mode;

 

(7)$(sort <list>)

Sorting, a string <list> word in ascending order, returns a sorted string;

 

(8)$(word <n>,<text>)

Take English, and returns the string obtain <text> first <n> words (starting at 1), if <n> <text> than large number of words, an empty string is returned;

 

(9)$(wordlist <s>,<e>,<text>)

Take word string, and returns the string obtain <text> first <s> th to <e> a word string;

 

(10)$(words <text>)

Count the number of words, and statistics returns the string <text> number of words;

Note: Get the last word in the string, using the $ (word $ (words <text>), <text>)

 

(11)$(firstword <text>)

The first word, obtain and return the string <text> in the first word;

NOTE: equivalent to $ (word 1, <text>)

 

3 filename handlers
(1) $ (dir <names ...>)

Take directory, the file name acquired from the sequence <names> directory and return portion;

Note: The directory part refers to the part before the last backslash, backslash if not, it returns "./";

 

(2)$(notdir <names...>)

Take file, and returns the acquired file portions from the file name sequence <names> in;

Note: The file section refers to the part after the last backslash;

 

(3)$(suffix <names...>)

Take suffix, the file name acquired from the sequence <names> and returns a suffix sequence of each file, without suffix empty string is returned;

 

(4)$(basename <names>)

Take the prefix from the file name acquired sequence <names> sequence and returns the prefix of each file, without prefix, it returns the empty string;

 

(5)$(addsuffix <suffix>,<names...>)

Suffix, the back <suffix> added <names> each word and return;

 

(6)$(addprefix <prefix>,<names...>)

Prefix, the front of the <prefix> added <names> each word and return;

 

(7)$(join <list1>,<list2>)

Connector, corresponding <list2> was added to a word in the <list1> after the word;

 

(8)$(wildcard <pattern...>)

Expansion of wildcards, variables, and citations for defining wildcards when failure function takes a string and returns the matching mode;

 

4 Other functions
(1) $ (foreach <var >, <list>, <text>)

The <list> are taken out one by one into the word <var> specified variable, then the expression is executed <text> included, each time the <text> returns a string, after performing a plurality of return foreach strings, strings separated by spaces;

### Makefile 内容
targets := a b c d
objects := $(foreach i,$(targets),$(i).o)

all:
@echo $(targets)
@echo $(objects)

### bash in enforcement Make
$ Make
A Bcd
Ao Bo Co Do


(2)$(if <condition>,<then-part>,<else-part>)

### Makefile 内容
val := a
objects := $(if $(val),$(val).o,nothing)
no-objects := $(if $(no-val),$(val).o,nothing)

all:
@echo $(objects)
@echo $(no-objects)

### bash execute the make
$ the make
a.o.
Nothing


(3)$(shell <shell-command>)

Execute a shell command, as a function returns the execution result;

 

(4) make the control function

$ (Error <text>): a fatal error, Makefile stop execution

$ (Warning <text>): output warning information, Makefile continue

 

(5)$(call <expression>,<para1>,<para2>,...)

<Expression> variable in expressions, such as $ (1), $ (2), ..., etc. are parameters <para1>, <para2>, ... are sequentially substituted, <expression> is the return value of the function call return value;

### Makefile 内容
log = "====debug====" $(1) "====end===="

all:
@echo $(call log,"正在 Make")

Perform ### bash in the make
$ the make
==== ==== Debug is Make ==== end ====

 

 


Eleven, Makefile examples
1 C language compiler project
Edit: main.o kbd.o command.o display.o
CC -o Edit main.o kbd.o command.o display.o

main.o : main.c defs.h
cc -c main.c

kbd.o : kbd.c defs.h command.h
cc -c kbd.c

command.o : command.c defs.h command.h
cc -c command.c

display.o : display.c defs.h
cc -c display.c

clean :
rm edit main.o kbd.o command.o display.o

.PHONY: edit clean


2 公共Makefile文件common.mk
#This is the common part for makefile

SOURCE := $(wildcard *.c) $(wildcard *.cc) $(wildcard *.cpp)
OBJS := $(patsubst %.c,%.o,$(patsubst %.cc,%.o,$(patsubst %.cpp,%.o,$(SOURCE))))
DEPS := $(patsubst %.o,%.d,$(OBJS))
MISSING_DEPS := $(filter-out $(wildcard $(DEPS)),$(DEPS))
CPPFLAGS += -MD

.PHONY : everything objs clean veryclean vc rebuild ct rl

everything : $(TARGETS)

objs: $ (OBJS)

clean :
@$(RM) *.o
@$(RM) *.d

veryclean: clean
@$(RM) $(TARGETS)
@$(RM) cscope.out
@$(RM) core*

vc: veryclean

ct:
@$(RM) $(TARGETS)

rl: ct everything

rebuild: veryclean everything

ifneq ($(MISSING_DEPS),)
$(MISSING_DEPS) :
@$(RM) $(patsubst %.d,%.o,$@)
endif

-include $(DEPS)


3 Makefile document prepared by training
(1) Preparations

Prepare three documents file1.c, file2.c, file2.h:

file1.c:

#include <stdio.h>
#include "file2.h"
int main()
{
printf("print file1\n");
File2Print();
return 0;
}
file2.c:

#include "file2.h"
void File2Print()
{
printf("Print file2\n");
}
file2.h:

#ifndef FILE2_H_
#define FILE2_H_

#ifdef __cplusplus

extern "C" {

#endif

void File2Print();

#ifdef __cplusplus

}

#endif

#endif


(2) Makefile file basic programming

helloworld: file1.o file2.o
gcc -o helloworld file1.o file2.o

file1.o: file1.c file2.h
gcc -o -c file1.c file1.o

file2.o: file2.c file2.h
gcc -c file2.c -o file2.o

clean:
rm -rf *.o helloworld
注:

gcc command, -c parameter followed by the file (.c or .cc) compiled into an object file (.o), - o parameter specifies the name of the output file (.o file by default);

 

(3) Makefile a file Advanced Programming - Using variables

OBJS = file1.o file2.o
CC = gcc
CFLAGS = -Wall -O -g

helloworld : $(OBJS)
$(CC) $(OBJS) -o helloworld

file1.o: file1.c file2.h
$ (CC) $ (CFLAGS) -c -o file1.c file1.o

file2.o : file2.c file2.h
$(CC) $(CFLAGS) -c file2.c -o file2.o

clean:
rm -rf *.o helloworld
注:

gcc command, -Wall -O -g parameters for configuring the compiler, -Wall parameter output all warnings, -O parameter optimization at compile time, -g debug parameter compiler version;

ARFLAGS: command parameters ar

CFLAGS: C language compiler parameters

CXXFLAGS: Parameter C ++ language compiler

 

(4) Makefile file Advanced Programming two - use function

CC = gcc
XX = g++
CFLAGS = -Wall -O –g
TARGET = ./helloworld

%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@

%.o:%.cpp
$(XX) $(CFLAGS) -c $< -o $@

SOURCES = $(wildcard *.c *.cpp)
OBJS = $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCES)))

$(TARGET) : $(OBJS)
$(XX) $(OBJS) -o $(TARGET)
chmod a+x $(TARGET)

clean:
rm -rf *.o helloworld
注:

$ (Wildcard * .c * .cpp) function returns a list of all acquisition and ending with .c or .cpp files;

$ (Patsubst% .c,% o, $ (SOURCE)) function to get all end with .c replaced with a new string and ending .o file list;


---------------------
Author: twc829
Source: CSDN
Original: https: //blog.csdn.net/twc829/article/details/72729799
Disclaimer: This article as a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/mazhenyu/p/11069688.html