The make command in Linux explains the collection

Source: Internet
Author: User

Make is a very important compilation command , both in Linux and in the UNIX environment. Whether you are developing your own projects or installing applications , we often use make ormakes install. With make tools, we can break down large development projects into more manageable modules, and for an application that includes hundreds of source files , using the Make and makefile Tools , you can easily Straighten out the complex interrelationships between the various source files. And with so many source files, it would be a disaster for programmers to compile a gcc command every time.

The Make tool automates the compilation process and compiles only the parts of the programmer that have been modified since the last compilation . Therefore, effective use of make and makefile tools can greatly improve the efficiency of project development. At the same time mastering make and Makefile, you will not face the Linux application software at a loss.
Unfortunately, in many books on Linux applications, this powerful but very complex compilation tool is not covered in detail . Here I will give you a detailed introduction to make and its description file makefile.
Makefile file
  

The most important and basic function of make tools isthrough the makefile fileTo describesource programThe relationship between each other and automaticallyMaintenanceCompile the work. and the makefile file needs to followsome kind of grammarTo be written, the file needs to explain how tocompilingAllsource files and connectGeneratedexecutablefile, and requires definitiondependency between source filesMakefile Fileis a common way for many compilers-including compilers under Windows NT-to maintain compiled information, but in an integrated development environment, users modify makefile files through a friendly interface.
In UNIX systems, it is customary to useMakefile as Makfile file。 If you want to use a different file as a makefile, you can use a similarthe following make command option specifies the makefile file
   $ make-f Makefile.debug
For exampleA program named Prog is generated by three C source files filea.c, FILEB.C, and FILEC.C and the library file LS compilation, these three files also contain their ownheader Files A.h, b.h, and C.h。 Typically, the C compiler will output three target files filea.o, FILEB.O, and FILEC.O. Suppose Filea.c and FILEB.Chave to declare a file named Defs, but FILEC.C not。 There are statements in FILEA.C and FILEB.C:
#include "defs"
Then the following document describes the relationships between these files:
---------------------------------------------------------
    #It is a example for describing makefile
PROG:FILEA.O FILEB.O FILEC.O

CC FILEA.O FILEB.O Filec.o-ls-o prog
FILEA.O:FILEA.C a.h defs
Cc-c FILEA.C
FILEB.O:FILEB.C b.h defs
Cc-c FILEB.C
FILEC.O:FILEC.C c.h
Cc-c FILEC.C
----------------------------------------------------------
This description document is a simple makefile file.
Note from the above example thatThe first character is a # behavior Comment line。 First onenon-commented linesSpecify prog byThree target filesFILEA.O, FILEB.O, and FILEC.O chains are delivered. The third line describes how toCreate an executable file from a file that prog depends on。 The next4, 6, 8 lines specify three target files respectively, and what theydependent. C and. h files and defs files。 and5, 7, 9The row specifies how thethe target depends onSet goals for the document.


   when the FILEA.C or A.H file is modified after compilation, the Make tool canAuto -Recompile FILEA.O, if between the front and back two compilations,Filea. C and A.H are not modified, and TEST.O still exist, there is no need to recompile。 This dependency ismulti-source files are particularly important in program compilation。 With this dependency definition, make tools can avoid manynot necessaryThe compilation work. Of course, the use of Shell scripts can also achieve the effect of automatic compilation, however,Shell scripts will all compile any source file, including the source files that are not necessarily recompiled, andMake ToolsCan be based on the targettime and Target of the last compilationDepends on the update time of the source file and automatically determine which should be compiledsource File
Makefile file as aDescription DocumentIt is generally necessary to include the following content:
Macro definition
source FileInter-dependency relationship between
Commands that can be executed
Allowed in makefilea simple macroRefer tosource files and their associated compilation information, also known in Linuxthe macro is a variable. When referencing a macro, you only need to add the $ symbol before the variable, but it is worth noting that if the variable name is longer than one character, you must add parentheses () to the reference.
The following are valid macro references:
$ (CFLAGS)
$
$Z
$ (Z)
   the last two references are exactly the same
It is important to note that somepre-defined variables for macros, in Unix systems,$*, [email protected], $? and $1zap
/USR/BIN/MAKE-DP | Grep-v Time>2zap
    diff 1zap 2zap
RM 1zap 2zap

LINT:DOSYS.C donamc.c file.c main.c misc.c version.c gram.c
$ (LINT) dosys.c donamc.c file.c main.c misc.c version.c
Gram.c
RM gram.c
Arch
Ar uv/sys/source/s2/make.a $ (FILES)
----------------------------------------------------------
Usually inThe description file should have the same definition as above to require that the output will be executedMake. In the execution ofMake commandAfter that, the output results are:
$ make
   cc-c version.c
Cc-c MAIN.C
Cc-c DONAMC.C
Cc-c MISC.C
Cc-c file.c
Cc-c DOSYS.C
  YACC gram.y
MV Y.TAB.C GRAM.C
   cc-c gram.c
CC VERSION.O MAIN.O donamc.o misc.o file.o dosys.o GRAM.O
-ls-o make
13188+3348+3044=19580b=046174b
   The final numeric information is the output of the Execute "@size make" command。 Reasononly the output will not have a corresponding command line, because the "@size make" command starts with "@", and this symbol suppresses the command line where it is printed.


The last few command lines in the description file
are useful for maintaining compilation information. Where the "print" command line is to print out all the changed file names after the last "make print" command was executed . The system uses a 0-byte file called Print to determine the exact time to execute the Print command, while the macro $? points to the file names of the files that were modified after the print file was changed . If you want to specify that the print command is executed and the output is fed to a specified file, you can modify the macro definition for P :
  

    make print" p= cat>zap "


Most software in Linux provides the source code , not the ready-made executable file , which requires the user to configure and compile the source program according to the actual situation of the system and its own needs, before the software can be used. Only by mastering make tools can we really enjoy the free software world of Linux.
==========================================
Preliminary study on Makefile
==========================================
There are two kernel configuration files for Linux, one is the implicit. config file, embedded in the main makefile, and the other is include/linux/autoconf.h, embedded in the various C source files, they are made by make config, make Menuconfig, make xconfig These procedures are created .

AlmostAllOfsource FileWill passlinux/config.h and Embedded autoconf.hIf a file dependency (. depend) is established as usual, as long as the updateautoconf.h, it will cause all source code to be re-yi.
To optimize the make process and reduce unnecessary re-yi,Linux has developed a dedicated MKDEP tool, using it to replace GCC to generate. DependFile.MKDEP header files such as linux/config.h are ignored when processing source files, identify the lines in the source file macro that have the "Config_" feature. For exampleIf there is a line like "#ifdef CONFIG_SMP", it will be output in the. depend file$ (wildcard/usr/src/linux/include/config/smp.h).
The file under include/config/is another tool split-include generated from the autoconf.h, which takes advantage of the config_ tag in Autoconf.h,generate files that correspond to MKDEP。 For example, if you have "#undef config_smp" in autoconf.hThis line, it generates a include/config/smp.h file with the content "#undef CONFIG_SMP". Thesefile nameOnly in. DependFile appears, the kernel source file isThey won't be embedded .Of EveryConfigure the kernel once, run Split-include one time. Split-include willCheck for old sub-filesContent to determine whether you want to update them. So, no matter what the autoconf.h modification date is, make does not re-update the Yi kernel as long as its configuration is not changed.
If the system'scompilation Yi OptionsChanges, Linux can also make incremental Yi. To do this, make every Yi a source file to generate a flags file. For example, when compiling Yi Sched.c, it is generated in the same directory.implied. sched.o.flags file。 It is a fragment of makefile when make enterswhen a subdirectory is compiled Yi, it searches for the flags fileAnd embed them in the makefile. These flags code tests that the current Yi option is not the same as the original,if the same, the corresponding target file is added to the Files_flags_up_to_date list, then the system removes them from the Yi Object table, gets the files_flags_changed list, and finally sets them as targets for updating.











The Make command under Linux is one of the most frequent commands used by system administrators and programmers. Administrators use it to compile and install many open-source tools through the command line, which programmers use to manage their large, complex project compilation problems. In this article we will use some examples to discuss the working mechanism behind make commands.

How make Works

For those who do not know the underlying mechanism, the make command receives the target like a command-line parameter. These goals are usually stored in special files named "Makefile", and the files also contain actions corresponding to the target. For more information, read a series of articles on how makefiles works.

When the make command executes for the first time, it scans the Makefile to find the target and its dependencies. If these dependencies are also targets, continue to establish their dependencies for these dependent scan Makefile, and then compile them. Once the main dependency is compiled, then the master target is compiled (this is passed in with the Make command).

Now, if you modify a source file, you execute the make command again, and it compiles only the target files associated with that source file, so it saves a lot of time compiling the final executable file.

Make command instance

The following is the test environment used in this article:

OS —— Ubunut 13.04Shell —— Bash 4.2.45Application —— GNU Make 3.81

Here is the project's content:

LS anothertest.c Makefile test.c test.h

Here's what's Makefile:

 All :  Test:    testtest.o :      ANOTHERTEST.O:clean    :     Test

Now let's look at some examples of the make command application under Linux:

1. A simple example

To compile the entire project, you can simply use it make or take a target with the make command all .

Test

You can see the dependencies the make command created for the first time and the actual target.

If you look at the contents of the catalog again, there are some more. o Files and execution files:

TEST.c test.h TEST.O

Now, let's say you've made some changes to the test.c file and re-use make to compile the project:

Test

You can see that only TEST.O is recompiled, but the other TEST.O is not recompiled.

Now clean up all the target files and the executable file test, you can use the target clean :

Testlsanothertest.c Makefile test.c test.h

You can see that all the. o files and the Execute file test have been deleted.

2. Use the-B option to make all targets always re-established

So far, you may have noticed that the make command does not compile files that have not changed since the last compilation, but you can use the-B option if you want to override this default behavior.

Here's an example:

 Done for 'all '.  Test

You can see that although the make command does not compile any files, it make -B forces all the target files and the final executable files to be compiled.

3. Print debug information using the-D option

Use the-d option if you want to know what actually happened when make was executed.

This is an example:

$ Make-d|Moregnu make 3.81Copyright(C)2006 Free software Foundation, inc.this are free software;See theSource forCopying conditions. There is NO warranty;Not even formerchantability or FITNESS for Aparticular PURPOSE. This program built forX86_64-pc-linux-gnureading makefiles ... Reading Makefile`Makefile ' ... Updating makefiles....considering target file`Makefile '. Looking forAn implicit rule for `Makefile '. Trying pattern rule with stem`Makefile '. Trying Implicit Prerequisite`MAKEFILE.O '. Trying pattern rule with stem`Makefile '. Trying Implicit Prerequisite`Makefile.c '. Trying pattern rule with stem`Makefile '. Trying Implicit Prerequisite`Makefile.cc '. Trying pattern rule with stem`Makefile '. Trying Implicit Prerequisite`Makefile.c '. Trying pattern rule with stem`Makefile '. Trying Implicit Prerequisite`Makefile.cpp '. Trying pattern rule with stem`Makefile '.--more--

This is a very long output, and you see I used the more command to display the output one page at a time.

4. Change the directory with the-C option

You can provide a different directory path for the make command, which switches the directory before looking for Makefile.

This is a directory, assuming you are in the current directory:

$ ls file file2 frnd frnd1.cpp log1.txt log3.txt log5.txtfile1 file name with spaces frnd1 frnd.cpp log2.txt log4.txt

But the Makefile file of the make command you want to run is saved in the. /make-dir/directory, you can do this:

`  Done for ` '/home/himanshu/practice/make-dir

You can see that the make command is first cut into a specific directory, executed there, and then switched back.

5. Use the-f option to treat other files as Makefile

If you want to rename the Makefile file, for example, named My_makefile or another name, we want make to take it as a Makefile, and you can use the-f option.

Make-f My_makefile

In this way, the make command chooses to scan my_makefile instead of makefile.








First, confirm that the GCC and make packages have been installed

You can use the Whereis command to view:

If the Whereis gcc and whereis make commands have results, you can continue to do so by installing both software.

Second, use GCC compile to run a HelloWorld program (only involves a single file)

You can write a C program in any directory and then compile and run it, I do this instance in my own home directory:

It then goes to the programming interface:

Press the keyboard "I" to enter the editing interface, and then enter the program:

Press ESC (enter command line mode), then enter ": Wq", the colon indicates the start input command, the letter W represents the save file, the letter Q represents the Exit Editor:

Press ENTER to exit the Vim editor, return to the terminal, following the compile run:

C. Run a multi-file program (containing main programs and subroutines) using GCC compilation

Here we have to write two C program files, a file inside write a function, another file in the main function called the first file function, as follows:

The EX_DISPLAY.C code is as follows, and after the same write, ESC then type: WQ exit:

Enter the following main function code:

Then save the exit, as follows to compile the run process:

Iv. using Makefile to solve the problem of multi-file compiling and running

As described in the red box in the previous section, if a program involves a lot of files, each has to write out, it is troublesome, so makefile appeared, please see the tutorial:

After entering makefile's editing interface, enter the following:

Then save the exit and run the Make command:

V. Comparison of Makefile and shell script methods

Some people say that I write all the previous commands into the shell script, not to achieve makefile effect, yes, the final effect is the same, but Makefile has these benefits:

    • Simplify the command of compilation execution (and no gcc–c process)
    • Once make, the next time only the modified files will be compiled, the other files will not be compiled

Others have some advantages, but this second advantage is too big for large projects!



The make command in Linux explains the collection

Related Article

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.