Linux Programming (3) MakeFile

Source: Internet
Author: User

1. In Linux, themake tool maintains program module relationships and generates executable programs . It can be re-compiled according to the modification of the program module into the intermediate code or the final executable program. The make command requires a text file named Makefile that defines dependencies between modules, specifies the order in which files are compiled, and the commands used to compile. Make and Makefile files enable automatic compilation of the entire project's source program files, greatly improving the efficiency of software development.

A simple Makefile file:

main:main.o module1.o module2.o             -o mainmain.o:main.c head1.h head2.h common_head.h            -c main.cmodule1.o:module1.c head1.h            - c module1.cmodule2.o:module2.c head2.h             - is a makefile

As can be seen, the basic unit of the makefile file is the rule, a rule specifies one or more target files, followed by the target file is compiled to generate the target file depends on the file or module, and finally the target file to build or update the command used.

It is important to note that if a row is a command, it must start with a TAB key. After the list of dependent files, add a semicolon (;), you can follow the command. Such as:

MAIN:MAIN.O module1.o module2.o; gcc main.o module1.o module2.o-o mainmain.o:main.c head1.h head2.h common_head.h
    -C MAIN.C

(1) The execution process of make

Assuming that the above makefile file and its related source files and header files are all in the current directory, execute the make command to start the automatic compilation.

Make first in the current directory looking for a file named Makefile, after finding, in the current directory to find the first line in the target file main, found no, go to find the generated main file depends on the file is: MAIN.O module1.o MODULE2.O, not found, and then skips the second line of the compile command. Navigates to line 2nd, the destination file in line 3rd is MAIN.O, but the source and header files it relies on are found in the current directory, and the 4th line is executed to generate the MIAN.O file. Make navigates to line 5th and discovers that the target file module1.o not, but the file it depends on is found, then executes the compile command on line 6th, generates MODULE1.O, and the next two lines are similar. Make then navigate to the last line and find the comment line, ignoring it. Make goes back to line 1th, when the dependent files are generated, then executes the second line of the compile command, and finally the target file main is generated.

The output from execute make is as follows:

GCC----o main            

(2) Assuming that you have modified the header file Head1.h and then executed make, how does this work?

Make first in the current directory looking for a file named Makefile, find, and then in the current directory to find the first line of the target file main, found that already exists, and then look for the main dependency file: main.o module1.o module2.o, found also exists. Make starts comparing the target file with the modification time of main and its 3 dependent files, and finds that the modification time of main is later than its 3 dependent files, so make considers the target file main to be up-to-date, so there is no need to execute the 2nd line command to generate the target file main.

Make navigates to line 3rd, and since the header file Head1.h has just been modified, causing Head1.h to be modified more than MAIN.O later, make considers that the target file main.o is obsolete, and executes the command 4th line to generate a new MAIN.O file. Then make navigates to line 5th, finds that Head1.h is newer than MODULE1.O, and generates a new MODULE1.O for the command that executes line 6th. Make then navigates to line 7th, after comparing the file modification time, to determine the command not to execute the 8th line.

After scanning the makefile file from start to finish, make starts to backtrack, and when it goes back to the 1th line, it finds that the MAIN.O MODULE1.O has been modified more than the target file, and then executes the 2nd row of commands, resulting in a new version of Main.

Note: 1) The command line can be inserted between any number of empty lines, the blank line will also press TAB, 2) If a line is too long, you can enter a backslash (\) before the end of this line, the rows connected by it are treated as a row, and 3) when Makefile is named as a different file, You should explicitly tell make which is a makefile file, such as: Make-f othername;4) Generally put the last file to be generated in the target file list of the first rule.

2. Composition of the Makefile file

(1) Display rule: Indicates the target file, the dependent file, the command used to generate or update the target file;

1) Makefile the symbol "$" has special meaning, need to sign "$" place, need to write "$$".

foo:foo.c | somelib     -o foo foo.c somelib

| The previous file is a normal dependent file, and if FOO.C is outdated, it will cause Foo to regenerate, and if later files become obsolete, Foo will not be regenerated.

2) Command line properties

After the TAB key Plus + 、-、 @, the meaning is as follows:

-: In order to execute this command line if the Far East error, continue to execute without exiting make;

+: The bank command is always executed, even if the make command is run with the-N,-Q,-t option;

@: The content of the command is not printed on the screen when you execute a stupid command

Example: Find FILE.O obsolete, first back up the obsolete FILE.O to/tmp, and then generate a new target file.

file.o:file.c hea1.h head2.h     -MV FILE.O/tmp    -C file.c

And the first execution of the FOO.O does not exist, the MV command error, but will continue to execute ("-" role).

3) Pseudo-target: does not require the actual file to be generated, but to let make perform some auxiliary commands, such as printing information, deleting useless intermediate files, etc.

Clean :     -rm-f *.O

When make scans to line 1th in the above two lines, finds that there is no dependent file, so it is always considered up-to-date so that it does not execute the 2nd line of the command, you can use the command "makes clean" after the shell prompt to execute the "clean:" statement.

The above command will not execute if a clean file exists in the current directory. You can declare a "clean" target as a pseudo-target. The method is: use it as a special goal. Phony "dependence. When writing a rule for a pseudo-target, you first need to declare that the target is a pseudo-target, and then the rule definition of the pseudo-target.

. Phony:cleanclean:     -rm-f *.O

This allows the RM command to be executed regardless of whether there is a "clean" file in the current directory that enters "make clean".

In one directory, if you need to generate multiple executables, you can use a pseudo-target called "all" as the final target, and its dependent files are the executables that need to be created.

all:program1 program2 program3. phony:allprogram1:program1.c utils.h    -o program1 program1.cprogram2:program2.c    -o Program2 program2.cprogram3:program3.c comm.h utils.h    -o program3 program3.c

4) Special targets

. Phony: Target ". Phony "All dependencies are used as pseudo-targets, and when the make command is used to set this goal, the commands in this target rule are unconditionally executed regardless of the existence of the target file.

. IGNORE: For Target ". IGNORE "followed by the dependent files, the commands that generate these dependent files are executed without error, and make ignores the error to continue execution.

. Suffixes: The dependency of the target is considered a list of suffixes to use when checking the suffix rules.

. SILENT: When you execute a command that generates dependent files for a dependent file on this target, make does not print out the command that is executed. If no dependent files are followed, the execution of all files in makefile is not printed.

. Precious: If make is terminated by the kill command or unexpected, the target's dependent files are not deleted, and if the dependent files are intermediate files, they are not deleted when they are not needed.

. Intermediate: The dependent file for this target is treated as an intermediate file when make executes.

5) rules that contain multiple targets

A multi-objective rule means that all targets have the same dependent file.

module1.o module2.o module3.o:command.h# equivalent to module1.o:module1.c     -C module1.c-o    module1.omodule2.o:module2.c-C module2.c-o module2.omodule3.o:module3.c     -C Module3.c-o MODULE3.O

6) Search Catalog

Make uses the variable "VPATH" to perform a dependent file search directory, which specifies the search path for all files in the makefile, including the rule's dependent and target files.

Define the variable "VPATH", using a space or colon (:) separate multiple directories that need to be searched.

VPATH =/USR/SRC; /headers

This specifies two search directories for all rules.

You can also use make's "vpath" keyword to set the file search directory, you can specify a different search directory for different files. How to use:

Vpath <pattern> <directories> #为符合模式 <pattern> files Specify the search directory <directories>

Vpath <pattern> #清除符合模式 <pattern> Search Directory of files

Vpath #清除所有已设置好了的文件搜索目录

<pattern> contains the "%" character, meaning match 0 or several characters, such as "%.h" to match all files ending with ". h".

# Make in ".. /headers "Directory Search all with ". h"%.h. /headers

If the same <pattern>,make appear in successive Vpath statements, the search is performed in the order in which the Vpath statements are executed.

(2) Implicit rules: rules that are automatically deduced by make based on the target file. Make automatically generates target dependent files and commands that generate targets based on the file name of the target file. Such as:

module1.o:head1.h #等价于如下规则module1. o:module1.c head1.h     -C Module1.c-o MODULE1.O

Implied rules involving the C language:

# target file without suffix program:header1.h header2.h# implied rule program:  program.c header1.h header2.h    gcc - o program program.c# make can be expressed as (CC defaults to cc,cflags default to -o,[email protected] refers to the target file,$< refers to the first dependent file): $ (CC) $ ( CFLAGS) [email protected] $<

#以. o End of target file Program.o:header1.h header2.h #隐含规则program. o:program.c header1.h header2.h     gcc -C program.c-C $< [email protected]

(3) Use variables: You can use a string to represent a text string. When a variable is defined, makefile is executed with the make explanation, and the string is replaced with the corresponding text string.

The general form of variables defined in makefile is: Variable name assignment value

1) How the variable is referenced: $ (variable name) or ${variable name}

2) Define variables: Two types of variables: recursive expansion variable (assigned by "=") and immediately expand variable (by ": =" Assignment)

Foo == = Huhall:    @echo $ (foo)
#这种定义的好处是: This variable can be used when the variable is undefined
# Disadvantage: May cause a dead loop, such as: CFLAGS = $ (CFLAGS)-O

x: = Fooy:= $ (x) Barx:= laterall:    echo $ (x) $ (y)
# expands immediately when defined, rather than when referencing the variable.

CFLAGS: = $ (include_dirs)-O
Include_dirs: =-lfoo-lbar
# The value of Cflags is "-O" instead of "-lfoo-lbar-o" because Cflags is expanded immediately when defined,
# and the variable include_dirs is not defined at this time, so $ (include_dirs) is empty

Conditional assignment "? =": This variable is assigned only if the variable is not previously assigned.

Foo? = bar# If the variable "FOO" is not defined before, assign it a value of "bar", otherwise it will not change its value

The Append assignment operator "+ =" implements an append operation to a variable value.

Objects-+ = another.o# adds the string "another.o" to the variable "objects  " The end of the original value, separated by a space from the original value.

3) commonly used pre-defined variables

Macro Name Initial value Description
Cc Cc The compiler used by default
CFLAGS -O Options used by the compiler
Make Make Make command
Makeflags Empty Options for Make command
SHELL The shell type used by default
Pwd Current directory When you run the Make command
Ar Ar Library Management Commands
Arflags -ruv Library Management Command Options
Libsuffix -A The suffix of the library
A A The name of the library extension

# Original Rules module1.o:module1.c Head1.h     The gcc -c module1.c# is changed to the following rules, CC is a predefined variable for the system and can    be used directly with module1.o:module1.c head1.h-c module1.c# Can change the values of predefined variables module1.o:module1.c head1.h    gcc    -C module1.c

4) Makefile automatic variable, the value can be changed dynamically during make operation

[email protected]: Represents the target file name in a rule, if the target is a document file, it represents the file name.

file1.o file2.o:header.h     CP [Email protected]/backup# function: When the target file is out of date, back up the original target file to the/backup directory, and then re-raw # into a new target file, when the need to update FILE1.O ( FILE1.C than FILE1.O new), [email protected] is equal to file1.o,file2.o similar # The above implied rule is equivalent to    the following file1.o:file1.c header.hCP [Email protected]/backup    gcc -C file1.c-o file1.ofile2.o:file2.c    header.h CP [Email protected]/backup    gcc -C file2.c-o file2.o

$%: When the rule destination file is a static library file, $% represents a member name for the static library. If the target is not a static library file, the $% value is empty

#规则目标是foo. A (BAR.O), the value of $% Bar.o,[email protected] is FOO.A

$<: The first dependent file name in a rule, if an implied rule is used, the value of $< is the first dependent file name introduced by the implied rule.

file1.o file2.o:header.h     CP [Email protected]/backup# when file1.o obsolete, the rule is equivalent to file1.o:file1.c    header.hcp [email protected]/ Backup     gcc -C file1.c-o file1.o# the first dependent file name in the rule, that is,the value of $ < is file1.c, not header.h.

$>: Applies only to static library files, and values are library names. For example, FOO.A (BAR.O), $% is bar.o,[email protected] The value is foo.a,$> and FOO.A. The non-static library file is empty.

$?: all new dependent file lists, separated by spaces, than the target file. If the target is a static library file name, the library member is represented.

$^: A list of all dependent files in the rule, separated by spaces, and the duplicate dependent files are removed.

$+: Similar to $^, but retains the recurring files in the dependent files, mainly used in the cross-referencing of the library when the program links

$*: Its value is the name of the destination file after the suffix is removed. For example: The target file module1.o, the $* value is Module1.

file1.o file2.o:header.h     gcc -c $*.c-o [email protected]

Note: The above automatic variables can only be used in the rules command, if you want to use in the target file list or the list of dependent files, to precede them with a $, such as $$*

FILE1.O file2.o: $$*. C header.h    gcc -C $*.c-o [email protected]# when processing the destination file for file1.o,$$* and $ * represents file1, when processing the target file file2.o, is File2

(4) file indication: Contains: 1) contains another makefile (equivalent) in one makefile, 2) specifies a valid part in makefile (equivalent to precompiled # if) in some cases, 3) defines a multiline command.

Example: Using a conditional statement to determine the variable "CC", if the value is "GCC", then use the library "Libgnu" when the program links, otherwise do not link any library.

LIBS_FOR_GCC =-= ifeq ($ (CC),gcc) libs=$ (LIBS_FOR_GCC)Else libs=$ (normal_libs) endiffoo:foo.c    -o foo foo.c $ (LIBS)

(5) Note: The content after the # character in Makefile is treated as a comment and can be represented by a backslash plus # (\#) when using the character #.

3. Using libraries

When a link is delivered to an executable file, if the generic. o file is linked, the contents of the entire. o file are inserted into the file, and if the link is a library, only the variables and functions required by the program are found in the library and loaded into the executable file.

A file in a library is generally called a member of a library, and is represented by a library name (member name)

MYLIB.A (file. O) #表示静态库myli. A (the dynamic library ends with. So) has a file named FILE.O. 

Static libraries are typically maintained and managed using the AR command. When you create a library, you use the library name as the destination file, and the file you want to put in the library as a dependent file, in the following format:

Library Name: library name (member 1) library name (member 2) ... or library name: library name (member 1, member 2 ...)

Next, enter the command: Ar-ruv Library name target file name

Example: Add file1.o, FILE2.O, file3.o three files to the Mylib library

mylib:mylib (FILE1.O)     gcc -c file1.c    ar -ruv mylib file1.o    rm -F file1.omylib: Mylib (FILE2.O)    gcc -c file2.c    ar -ruv mylib file2.o     RM -f file2.o ...

The above rules can be simplified by using automatic variables:

mylib:mylib (file1.o file2.o file3.o)     ar -ruv [email protected] $?    RM -F $? file1.o:file1.c     gcc -c file1.cfile2.o:file2.c    gcc -c file2.cfile3.o:file3.c      GCC -C file3.c

Further use of implicit rules simplifies:

mylib:mylib (file1.o file2.o file3.o)     ar -ruv [email protected] $?    RM -F $?

Make also establishes a corresponding implicit rule for library operations, similar to the following:

$ (AR) $ (arflags) [email protected] $?    RM -F $? # AR, arflags are predefined variables for make, the initial values are AR,-ruv

Thus the above rules are further simplified:

Mylib:mylib (file1.o file2.o file3.o)

4. Make command parameters

-C dir Before reading the makefile, switch to the Dir directory and use it as the current directory
-D All debug information is printed out when make executes
-E System environment variables are not allowed to be re-assigned in makefile
-F filename Use the specified file as the makefile file
-I. Ignore errors generated when executing commands in makefile, do not exit make
-H Print out Help information
-K Execution of make does not terminate when execute command encounters an error
-N Print only the command you want to execute, but not the command
-O filename Specifies that the filename file does not need to be rebuilt, even if the dependency relative to it is obsolete
-P Print out all the data for make read makefile before the command executes, and print out the version information of make
-Q Ask mode, do not execute any command, make returns a query status value, 0 means no target needs to be rebuilt, 1 indicates there is a target to rebuild, and 2 indicates an error occurred
-R Ignore implied rules to make them ineffective, but do not cancel pre-defined variables that are inline
-R Suppresses the built-in predefined variables of make, which means that the implicit rule field loses meaning
-S Executes but does not display the command that is executed
-T Set the last modification time of all target files to the current system time
-V Print out version information for make

1. You cannot use a shared body variable as a function parameter, and you cannot return a function to a shared body variable, but you can work with a pointer to a shared body variable.
2. The C language allows memory to be used in bits in a struct, called a bit field.

The following struct requires that the bit segments after C be started from another storage unit:

struct bit_data{    int6;     int 4 ;     int 0 ;     int 4 ;     int D;    };

The following struct requires 8-bit forced idle of the 10~17 bit:

struct bit_data{    int6;     int 4 ;     int 8 ;     int 4 ;     int d:};

Linux Programming (3) MakeFile

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.