|
Blue Forest http://www.lslnet.com at 10:18 on June 6, 2006
Introduced a makefile (find online), please come to see whether accurate crop.
Introduced
This paper will begin with an introduction to why your C source code files separated into several independent reasonable, and when necessary, how can the good hours. Make then will tell you how to make your GNU compiler and linking steps automation. Make the tools for other users, although the use of other similar tools to do the necessary adjustments to the contents of this paper is still very useful. If you have doubts about their own programming tools, the actual test, but please powerful reading user manual.
1) Multi document projects
1.1 Why use them?
First, many documents in projects where the benefits?
They appear to make things very complicated. Also header documents, but also extern statement, but needs to find out if a document, you have to search more documents. But, in fact, we have a very powerful reason to support a project down into small pieces. When you change his code, the compiler need to be completely redesigned to generate a new compiler executable files. However, if your project is divided into several small papers, when you change a document, the objectives of other source documents (object files) already exist, so there was no reason to re-editing them. You only need to do that again translation of the documents had been altered, and then re-connect all the goals document space. In large projects, this means a very long (minutes to hours) to re-translation reduced to 10, plus a simple adjustment. As long as they pass the basic plan, the project will be divided into a small number of documents you will find a section of the code more easily. Very simple, you put your code under the code assigned to the role of different documents. When you look at some code, you know exactly what the document to find it. File a package from the many goals (Library) than from the great goal of a single document generated much better. Of course, this is really an advantage of the system is that you have to decide. However, when using gcc/ld (a GNU C Compiler / connector), a package linked to a procedure, in the linking process, it will not try to connect to the part not used. It can only put a complete package from the target document excluded. So if you reference a goal of a program package stall any one symbol, then this goal will be linked into the whole document. If a package has been very good of the decomposition, then on the link, the executable files will be more than a paper target from a package of documents to be much less connected. Because your process is modular, document sharing between the parts being reduced to a minimum, it has many advantages -- could easily be traced to chinch, these modules often can be used in other projects Lane, while others can more easily understand your code is a dry anything. Of course, in addition to many other benefits : :
1.2 decomposition when your project
Obviously, anything decomposition is unreasonable. As "the world, you" would not be such a simple procedure, because there are no really separable. Testing procedures used for the decomposition is no small point. But generally speaking, when decomposition contribute to the layout of the project, the development and accessibility, I would take it. In most cases, these are applicable. (The so-called "world, you better," both 'Panorama world', is a programming language used on the example of a procedure, it will be shown on the screen in his' Panorama world '. Is the most simple procedure. ) If you need to develop a large project, in the beginning, you should consider how to achieve it, and students into several documents (appropriate name), to let your code. Of course, in the process of developing your projects, you can create a new document, but if you do so, you may note changes to the original idea, you should consider whether the whole structure needs to be adjusted accordingly. For medium-sized projects, of course, you can use these techniques, you can then start importing your code, your code more difficult to manage the moment they are divided into different files. But in my experience, the mind at the beginning of a rough, and try to comply with it, or in the development process, along with the need to amend the procedures, the development will become easier.
1.3 How decomposition project
Describe, it is my personal opinion, you can (maybe you really? ) Do in other ways. This will be the touchstone to the coding style, and we have not stopped the debate on this issue. Here, I just like to give my own practice (which also gives the reasons for doing so) :
I) Do not use a header at the number of source documents (exceptions : the package header). A source with a header definition of the manner in which documents will be more effective and more easily traced. Otherwise, a change in the structure of the source document (and the header) on several documents must be translated.
Ii) If yes, it can be used at more than one document with a header in the source document. Sometimes an open call to the function prototypes, type definitions, etc., from their C source separation is a very useful document. Open symbols loaded document using one header with another private loaded symbols of this means that if you change the internal structure of the source document, you can not only re-editing and re-editing it using the open source documents and other documents header.
Iii) not defined in a number of plots document header information. If, in one document #include another header, but the header information is not the same plots twice to import. The reason is if you later change this message, you simply need to change it once, not another one plots the search and change information.
Iv) a source document, the document #include those statements at the source of all the document header. As a result, you header in the source document and the document made contradictory statements of certain functions can be easily found compiler.
Notes 1.4 for the common mistakes
A) Definitions website (Identifier) in the source document contradiction : C, variable and function of the state is the lack of utilities in the province. Therefore, the C source files are applied to any other source code exists in the stalls of the overall (global) variables and overall function, which does not change even if the volume or file a statement or function prototype. So you must ensure that the file can not be used with the two symbols with a name, or there will be links in the translation error or there will be a warning. A common approach is to avoid the mistakes of symbols to insert it in the source document with the relevant prefix. For example :
All functions are gfx.c Lane added prefix "gfx_." If you are very careful you the decomposition process, the use of meaningful function name, and the overall situation is not excessive use of variables, of course, it should not be an issue. It is defined to prevent a mark in the source document to be seen outside, in its definition add keyword "static." In a file for internal use only, not used for other files are a simple function is very useful.
B) Multiple Symbol : header definition of the stalls will be verbatim #include replacement to the location of your source document. Therefore, if the header #include stall was the source of more than one document, the header will appear in the definition of all the stalls every relevant source documents. This can cause them to Lane symbols are defined more than once, thus resulting in the wrong link (see 1).
Solution : Do not stall Lane header definition of variables. You just need to stall Lane header in their statement at an appropriate C source document (which should #include that header stalls) Lane definition they (once). For beginners, it is very easy to confuse the definitions and declarations. The statement is to tell the compiler symbol statement they should exist, and must be specified types. However, it does not make a compiler allocate storage space. And the meaning of the compiler is doing with the storage space allocation. As a statement and not a definition, in a statement before sending up a keyword "extern." For example, we have a program called "counter" variable, if the public wants it to become, in a FOSS procedure (only one there) : it is the beginning of the definition of "int counter;" and then stalls Lane header in the relevant statement it : "extern int counter;." Function prototypes Lane implied extern means and not worry about this problem.
C) The definition of plots, plots statement contradictions types :
Please take into account that if a C-source document and bh #include two stalls ah, ah stall again #include a bh (bh stall because ah need some definition of the type), what will happen? Then the C source of the documents #include bh twice. So every one of the # bh have taken place on two occasions, a statement every two months, and so on. Theoretically, because they are exactly the same as the copy, so there should not be any problem, but in actual practice, this does not conform to the syntax of C, there may be mistakes in translation, or at least a warning. The solution is to establish a permanent stall on the header of each source document only contain one. We used as a pre-processor to achieve this aim. When we entered the header of each stall, stall # 1 for the header to get broad directives. This was not only in order to get broad definition under the premise that we are really going to use the stalls in the main header. In actual application, we can simply put the code on a header following a stall in the beginning part :
#ifndef FILENAME_H
# FILENAME_H
Then the following code on his final :
#endif
Header stalls with (the capital) to replace the above FILENAME_H, stalls were used instead of the bottom line point. Some people like to add #endif #endif Notes to remind them of what is meant by this. For example :
#endif LEAVES OF 13 SPECIES OF LAURACEAE #ifndef FILENAME_H */
I personally do not have the habit because it is very obvious. Of course, depending on the style, harmless.
You just need to be translated in those stalls header into the wrong skills, but also joined by some header stalls have no losses, in the end it is a good habit.
Re-editing more than one document projects 1.5
Clear distinction between compilation and linking is very important. Compiler used to produce some form of objective source document (object files). In this process, the external symbols of reference has not been explained or replacement. We then use connector to connect these objectives documents and packages with the standards specified in your package, as a final link Health enforceable procedures. At this stage, one of the objectives of the document by reference to other documents to explain the symbols, and can not be explained by reference to the report, the general format of the report is the wrong message out. On the basic steps should be your source of a document translated into a target document form, the final goal of making some necessary documents with the executable files and link them together into a package. How is your specific compiler decision. Here I can only give gcc (GNU C Compiler) of the order, which is likely to apply to your non-gcc compiler.
Gcc is a multi-purpose tool. Call it the time of need other components (pretreatment procedures compiler.
Portfolio procedures connector). Call depend on imported components which are specific to the type of document you send to the switch. Generally speaking, if you just give it C source document, which will pre-compiler, which combined all the documents and then link them together into one document the target executable files (usually generated document has been named a.out). You could of course do so, it would undermine many of our projects is divided into a number of documents have been good. If you give it a-c switch, gcc only to the documents compiled object files, and source documents in their names but by the suffix. " C "." Cc "into." O. " If you give it a list of targets, documents, gcc there will be linked into the executable files, the default file name is a.out. You can change the default name appears -o told you specified file name. Therefore, when you change a source document, you need to re-translated it : 'gcc-c filename.c' then you have to re-link the item : 'gcc -o exec_filename *.o'. If you change a header stall, you need to re-editing the source of all #include stall this document, you can use 'gcc-c file1.c file2.c file3.c' then the same as connecting pieces. Of course, doing so is very cumbersome, it is fortunate that some of the tools become more simple steps. The second part is on the GNU tools : Make a tool.
2) Make GNU tools
2.1 The basic structure makefile
GNU Make main task is entered in a text file, makefile. This document Lane, which is the main document (the 'target' purpose) from which other documents ( 'dependencies' on paper), produced and what order to carry out the selection process. With such information, make checks on the disk in the paper, if the purpose of the stamp paper (or changes to the document generating the time) than at least one of its documents on the old, make the implementation of the corresponding order to update documentation purposes. (Purpose of the final document may not be enforceable stalls, it can be any document. ) Makefile generally called "makefile" or "Makefile." Of course, you can make other documents were designated the command line. If you do not specifically designated, it will seek "makefile" or "Makefile", it is the simplest to use these names.
Makefile contains a series of rules, as follows :
For example, consider the following makefile :
If so, if so, begin makefile
Myprog : foo.o bar.o
Gcc foo.o bar.o -o myprog
Foo.o : foo.c foo.h bar.h
Gcc-c foo.c -o foo.o
Bar.o : bar.c bar.h
Gcc-c bar.c -o bar.o
If so, if so, the end of makefile
This is a very basic makefile -- make from the top, put a face on purpose, 'myprog', as its main goal (the latest one it is always necessary to ensure their ultimate goal). Paper documents as long as the rules' myprog 'over the documents' foo.o' or 'bar.o' of any old, the next order will be implemented. However, the inspection documents and bar.o foo.o the stamp, it will be down to search those goals as foo.o bar.o documents or rules. Foo.o find it on the rules, the document is on paper foo.c, and bar.h foo.h. Now again it could not find documents on the formation of these rules, it has begun inspection of these disk stamp on the document. If any one of these documents over the stamp foo.o new order 'gcc -o foo.o foo.c' will be implemented, so as to update the document foo.o. Next bar.o doing similar examination of the documents, and on paper in the paper bar.c bar.h. Now, back to make 'myprog' rule. If any one of just two rules to be implemented on the need to rebuild myprog (as one of them. O stalls will be more than 'myprog' new), it will connect the order was executed.
Hope here, you can make use of tools to establish procedures to see the benefits -- the previous chapter, all inspection steps were cumbersome for you to do : make inspection stamp. A simple change in the source document you will have it re-translated documents (as a result. O rely on the document. C), then re-connect the executable files (as a result. O document has been altered). In fact, the real benefit is when you change a header in the stall when you no longer need to remember -- that source documents on it, because all the information in the makefile Lane. You can make a very light-hearted re-translation of all those who depend on the result of a change in the source document and the document header, if needed, and then re-connect. Of course, you in your makefile to determine the accuracy of the rule is written, only those listed in the source document's header was #include stalls : :
2.2 preparation make rules (Rules)
The most obvious (and most simple) is a method of preparation of the rules of the look of a source document, as they document the objectives, and the C source code and documentation as it stalls #include header on the document. But you have to take the rest of these stalls #include header in the header stalls on the list of documents, which are included in the document included in the documents : : Then you will find more and more of the document management, then your hair began falling out of your temper began to deteriorate, the color of your face into the dish. You take on the road beginning with the collision between wire pole, and finally you destroy your computer monitors stop programming. No more vulnerable to a low of 20.9? Of course! Compiler to be! In the translation of each source document, it should know what kind of header the stalls. Gcc used when using M switch, it will give you a document to export its C rules, as the target document, which should be #include C. documents and all documents will be used on the document header. Pay attention to the rules will be joined header documents, including by the angle brackets (`< '`>;'), and double quotation marks ( `" ') surrounded by paper. In fact, we can be quite sure that the stall system header (eg stdio.h, stdlib.h, etc.), we will not be changed. If you convey to gcc-M -MM to replace those who use its buildings, including the header stall angle will be covered. (This will save some time compiler) gcc export rules do not contain orders; You can not write into your orders or anything. Let's make use of it and that the rule implied (refer 2.4 below).
Variable 2.3 Makefile
Makefiles Lane, which mainly includes the above-mentioned rules. They comprise the other variable is the definition of the East and West. Lane variables like a makefile environmental variables (environment variable). In fact, the environmental variables in the process of being interpreted to make make the variables. These variables are sensitive capitalization, the general use of capital letters. They can be used from virtually anywhere, they can also be used to do many things, such as :
I) Document storage of a table. In the above example, the rules contain executable files generated documents were used on some targets. The rules of order shop in the same order as those documents were transmitted to the gcc parameter. If it was here that the objective of the use of a variable to store all documents, and a new document will become the target of simple
Less prone to mistakes.
Ii) the executable files were stored. If you are a non-gcc items to be used in the system, or if you wish to use a different compiler, you must use a compiler which will be replaced with the new name of the compiler. However, if the compiler used to replace one variable, and then you only need to change a place, it will have all parts of the order were changed.
Iii) storage compiler Flag. Assuming you want to send you all a group of the same order of the compiler options (for -Wall O g); If you keep this group of choice into a variable, then you can use the compiler's call on all local variables. And when you have the option to change, you only need to change this in a local variable in content. To set a variable, you need only the beginning of his writing in the name of this variable, with a = area on its back with you to set the value of this variable. After you use the same variables and write a $ symbols, is sitting behind Lane variables including its name. For example, at the bottom, we have to rewrite it again in front of the makefile used variables :
If so, if so, begin makefile
OBjs = foo.o bar.o
CC = gcc
CFLAGS = O g -Wall
Myprog : $ (OBjs)
$ (CC) $ (OBjs) -o myprog
Foo.o : foo.c foo.h bar.h
$ (CC) $ (CFLAGS) - c foo.c -o foo.o
Bar.o : bar.c bar.h
$ (CC) $ (CFLAGS) - c bar.c -o bar.o
If so, if so, the end of makefile
Some good set of internal variables and their definition of the content of each procedure. $Three variables are more useful, and $^ $< (including these variables do not need to live in brackets). $Purpose file name extension of the current rules, $< extended into the first on the list on paper and $^ expansion on the entire list (which get rid of all the duplicate documents). Use these variables, we can make the above makefile wrote :
If so, if so, begin makefile
OBjs = foo.o bar.o
CC = gcc
CFLAGS = O g -Wall
Myprog : $ (OBjs)
$ (CC) $^ -o $
Foo.o : foo.c foo.h bar.h
$ (CC) $ (CFLAGS) - c $< -o $
Bar.o : bar.c bar.h
$ (CC) $ (CFLAGS) - c $< -o $
If so, if so, the end of makefile
You can use variables to do many other things, especially when you use them and when mixed function. If the need to further understanding, please refer to GNU Make Manual. ( 'Man make' and 'man makefile')
2.4 implicit rules (Implicit Rules)
Please note that in the above example, a few have. O document are the same order. From. C and related documents will create. O, which is a standard step. Actually make some already know how to do -- it's called the hidden rules within their own rules to tell it when you did not give the orders, how we should do. If you take orders from their generation bar.o foo.o and delete the rules, make the rules will find it implied, then find an appropriate order. It will be used to order some caveats, according to what you think you can set it as CC : It uses variable compiler (as in the previous example), and CFLAGS variable transmission (for the C compiler, C + + compiler transparencies CXXFLAGS), CPPFLAGS (C pre-processor Flag). TARGET_ARCH (now do not consider this), then it joins the Flag '- c', the latter with variable $< (one on), then Flag '-o' $with variables (objective document).
C compiler is a specific order will be : $ (CC) $ (CFLAGS) $ (CPPFLAGS) $ (TARGET_ARCH) - c $< -o $course, you need to be in line with your own definition of these variables. That is why the M or -MM gcc open relations with the output code can be directly used in a makefile Lane. 2.5 illusion purposes (Phony Targets) If you need to produce a final project two executable files. Your main objective is to produce two documents enforceable, but if the two documents are independent of each other -- one document in need of redevelopment does not affect another. You can use the "illusion of purpose" to achieve this effect. With the purpose of an illusion of a normal purpose is almost the same, but this document does not exist. Therefore, make the assumption that it will always need to be generated, and when it is dependent on the updated document, it will implement the rules that the command line. If we start the makefile imported :
Exec2 : exec1 exec2 which exec1 and all our aim as the two executable files. Make this' all 'as its main purpose, each implementation will try to' all 'update. However, since it has no rules by which to order a role called 'all' the actual document (in fact all is not on the actual disk), so this does not really change the regulations' all 'state. Since this document may not, therefore, make will try to update all the rules, so I check it on the exec1, exec2 need to update, if necessary, put them updated, so as to achieve our objective. False impression that the goal is to be used to describe a group of non-predetermined movements. For example, you want to make all of the deleted documents, you can makefile in the creation of such a rule :
Veryclean :
Rm *.o
Rm myprog
On the premise that no other rules' veryclean ', it will never be implemented. But if you explicitly ordered the use of 'make veryclean', as this will make it the main goal, the implementation of those orders rm. If your disk there is a document called veryclean, what will happen? In this time because there was no rule on the document, the purpose of this paper is the latest of (all the documents are already on most new), and so even if users have explicitly re-orders make it, and there will not be any incidents. The illusion which is the solution for all purposes (used. PHONY), which told them to check whether there is not to make a disk, do not identify any hidden rules, the goal needs to be designated directly assumption update. Makefile in the above rules incorporate the rules below this line include :
. . PHONY : veryclean
On it. Bearing in mind that this is a special make rules, make aware. PHONY is a special purpose, of course, you can incorporate it on purpose you wish to use any illusion that they know are false and make goals.
2.6 function (Functions)
Makefile Lane -- very similar to the function of the variables used it to the time you sign with the opening of a $ brackets, a few letters, a series of ballots, told the parameters separated by commas, brackets relations with the final end. For example, there is a GNU Make called 'wildcard' letter, it would have one parameter is a function of its launch into a list of all the parameters described in the documents, and documents with blank space between interval. You can use this order as indicated below :
SOURCES = $ (wildcard *.c)
It's all to be one '. C 'end of the list of documents, which could then be stored in variables SOURCES Lane. Of course, you must not result into a variable.
Another useful function is patsubst (patten substitude, for the initials for the match) function. It requires three parameters -- is a need for a matching pattern, and the second said what to replace it, and the third is a box separated from the need to be dealt with the word out. For example, after the above address that the definition of variables,
OBjs = $ (patsubst %.c, %.o $ (SOURCES))
SOURCES characters in this series will deal with all the characters (a series of papers), if it is the end '. C 'used'. O 'turn'. C 'replacement. Symbol% of the market will pay attention to here is assigned one or more characters, and it's always a matching string is called a 'stalk' (stem). In the second parameter, be interpreted as% of the match with the first parameter that stalk.
2.7 a more effective makefile
We are now using the study, we can create a very effective makefile. We need to finish most of the makefile can rely on the inspection did not have to do too much change can be directly used in the vast majority of projects Lane.
We need a basic makefile to build our procedures. We can let the current catalog search to find source documents, and assume that they are all our projects, either in a variable called SOURCES. If the document contains all the *.cc here, perhaps more insurance may be because the C + + source code documentation. SOURCES = $ (wildcard *.c *.cc) patsubst use, we can have a goal of documents from the source file name, and we need the translation of these objectives document. If both the source document. C documents, as well. Cc documents, we need to use the embedded phase patsubst function call :
OBjs = $ (patsubst %.c, %.o $ (patsubst %.cc, %.o $ (SOURCES)))
Call on the inside layer of the most patsubst. Cc suffix alternative document, the result was the outer patsubst Call, for right. C suffix paper alternative.
Now we can establish a procedure to build the executable files :
Myprog : $ (OBjs)
Gcc -o myprog ($ OBjs)
Further rules do not necessarily need to know how to have generated gcc object files (object files). Now we can have a set of rules on information :
Depends : $ (SOURCES)
$ Gcc-M (SOURCES) "; Depends
Here, if one is called 'depends' documents did not exist, or any other source than the one already in existence depends new document, a document will be depends Health%. Gcc from the document will be depends on the source documents containing the rules (M attention switches). Now we want to make these rules as part of the makefile stalls. Here the use of C language skills like #include system -- we should seek to make this document include makefile, as follows :
Include depends
GNU Make see this check 'depends' renewed purpose, if not, we will have to reconsider its order depends stalls. Then it will turn this group of (new) rules contain them, to continue to address the ultimate goal of 'myprog'. When he saw the myprog rules, it will check whether the objectives of all the documents to update the rules -- use depends, of course, the rules now is the updated.
In fact, this system is inefficient, because whenever a source document had been altered, the source of all the documents are pre-handle to create a new 'depends' document. It is not 100% safe, it is because when a header stalls had been altered, and not rely on information being updated. But on the basic work, it is also quite useful in this case.
2.8 a better makefile
This is a project I designed for the majority of my makefile. It should not be used in most revisions of the project Lane. I mainly use it in djgpp, it is a DOS version of the gcc compiler. So you can see that the implementation of the orders were, 'alleg' package, and RM-F variable reflect this point.
If so, if so, begin makefile
######################################
#
# Generic makefile
#
# By George Foot
Email : # george.foot@merton.ox.ac.uk
#
# Copyright (c) 1997 George Foot
# All rights reserved.
# Retain all copyright
#
# No warranty, no liability;
# You use this at your own risk.
# No insurance, no charge
# You use this, your own risks
#
# You are free to modify and
# Distribute this without giving
# Credit to the original author.
# You can change the distribution of this document and
# Without the need to honor what the original author.
# (Your nerve? )
#
######################################
Customizing ###
# The user
#
# Adjust the following EXECUTABLE is the target if necessary;
# Executable 's filename, and LIBS is a list of libraries to link in
# (Eg alleg, stdcx, iostr, etc.). You can override these on make 's
# Command line of course, if you prefer to do it that way.
#
# If necessary, adjust the following things. EXECUTABLE goal of the executable files, and BUFFER
# Package is a need to link the list (for example, alleg, stdcx, iostr etc.). Of course, you
# Coverage they can make the command line you want, no problem.
#
EXECUTABLE : = mushroom.exe
BUFFER : = alleg
# Now alter any implicit rules' variables if you like, eg :
#
# Now you want to change any changes to the implied rules of variables such as
CFLAGS = g -Wall -O3 -m486 :
CXXFLAGS : = $ (CFLAGS)
# The next bit is in your checks to see whether djgpp bin rm
# Directory; if not it uses del instead, but this can cause (harmless)
# `File Not found 'error messages. If you are not using DOS at all.
# Set the variable to remove something which will unquestioningly
# Files.
#
# Next, we will check your order catalog djgpp not rm order, and if not, we used del order to replace, it might give us the 'File not found' the wrong message, not what # uneventfully. If you are not using DOS, and set it into a document without deleted nonsense orders. (In fact, this type of step in the UNIX system is redundant, would only make it more convenient for DOS users. UNIX users can delete this line orders. )
ifneq ($(wildcard $(DJDIR)/bin/rm.exe),)
RM-F := rm -f
else
RM-F := del
endif
# You shouldn't need to change anything below this point.
#
# 从这里开始,你应该不需要改动任何东西。(我是不太相信,太NB了!)
SOURCE := $(wildcard *.c) $(wildcard *.cc)
OBjs := $(patsubst %.c,%.o,$(patsubst %.cc,%.o,$(SOURCE)))
DEPS := $(patsubst %.o,%.d,$(OBjs))
MISSING_DEPS := $(filter-out $(wildcard $(DEPS)),$(DEPS))
MISSING_DEPS_SOURCES := $(wildcard $(patsubst %.d,%.c,$(MISSING_DEPS)) \
$(patsubst %.d,%.cc,$(MISSING_DEPS)))
CPPFLAGS += -MD
..PHONY : everything deps objs clean veryclean rebuild
everything : $(EXECUTABLE)
deps : $(DEPS)
objs : $(OBjs)
clean :
@$(RM-F) *.o
@$(RM-F) *.d
veryclean: clean
@$(RM-F) $(EXECUTABLE)
rebuild: veryclean everything
ifneq ($(MISSING_DEPS),)
$(MISSING_DEPS) :
@$(RM-F) $(patsubst %.d,%.o,$@)
endif
-include $(DEPS)
$(EXECUTABLE) : $(OBjs)
gcc -o $(EXECUTABLE) $(OBjs) $(addprefix -l,$(LIBS))
=== makefile 结束 ===
有几个地方值得解释一下的。首先,我在定义大部分变量的时候使 用的是 := 而不是
= 符号。它的作用是立即把定义中参考到的函 数和变量都展开了。如果使用 = 的话,
函数和变量参考会留在那 儿,就是说改变一个变量的值会导致其它变量的值也被改
变。例 如:
A = foo
B = $(A)
# 现在 B 是 $(A) ,而 $(A) 是 'foo' 。
A = bar
# 现在 B 仍然是 $(A) ,但它的值已随着变成 'bar' 了。
B := $(A)
# 现在 B 的值是 'bar' 。
A = foo
# B 的值仍然是 'bar' 。
make 会忽略在 # 符号后面直到那一行结束的所有文字。
ifneg...else...endif 系统是 makefile 里让某一部分码有条件的 失效/有效的工
具。 ifeq 使用两个参数,如果它们相同,它把直 到 else (或者 endif ,如果没有
else 的话)的一段码加进 makefile 里;如果不同,把 else 到 endif 间的一段码加入 makefile (如果有 else )。 ifneq 的用法刚好相反。 'filter-out' 函数使用两个用空格分开的列表,它把第二列表中所 有的存在于第一列 表中的项目删除。我用它来处理 DEPS 列表,把所 有已经存在的项目都删除,而只保留缺少的那些。
我前面说过, CPPFLAGS 存有用于隐含规则中传给预处理器的一些 旗标。而 -MD 开关 类似 -M 开关,但是从源码文件 .c 或 .cc 中 形成的文件名是使用后缀 .d 的(这就 解释了我形成 DEPS 变量的 步骤)。DEPS 里提到的文件后来用 '-include' 加进了 makefile 里,它隐藏了所有因文件不存在而产生的错误信息。 如果任何依靠文件不存在, makefile 会把相应的 .o 文件从磁碟 上删除,从而使得 make 重建它。因为 CPPFLAGS 指定了 -MD , 它的 .d 文件也被重新产生。 最后, 'addprefix' 函数把第二个参数列表的每一项前缀上第一 个参数值。 这个 makefile 的那些目的是(这些目的可以传给 make 的命令行 来直接选用):
everything:(预设) 更新主要的可执行程序,并且为每一个 源码文件生成或更新一个 '.d' 文件和一个 '.o' 文件。 deps: 只是为每一个源码程序产生或更新一个 '.d' 文件。 objs: 为每一个源码程序生成或更新 '.d' 文件和目标文件。 clean: 删除所有中介/依靠文件( *.d 和 *.o )。
veryclean: 做 `clean' 和删除可执行文件。
rebuild: 先做 `veryclean' 然后 `everything' ;既完全重建。
除了预设的 everything 以外,这里头只有 clean , veryclean , 和 rebuild 对用户是有意义的。 我还没有发现当给出一个源码文件的目录,这个 makefile 会失败的 情况,除非依靠 文件被弄乱。如果这种弄乱的情况发生了,只要输入 `make clean' ,所有的目标文件和依靠文件会被删除,问题就应该 被解决了。当然,最好不要把它们弄乱。如果你发现在某种情况下这 个 makefile 文件不能完成它的工作,请告诉我,我会把它整好的。
3 总结
我希望这篇文章足够详细的解释了多文件项目是怎么运作的,也说明了 怎样安全而合理的使用它。到此,你应该可以轻松的利用 GNU Make 工 具来管理小型的项目,如果 你完全理解了后面几个部分的话,这些对于 你来说应该没什么困难。 GNU Make 是一件强大的工具,虽然它主要是用来建立程序,它还有很多 别的用处。如果想要知道更多有关这个工具的知识,它的句法,函数, 和许多别的特点,你应该参
看它的参考文件 (info pages, 别的 GNU 工具也一样,看它们的 info pages. )。
介绍
本文将首先介绍为什么要将你的C源代码分离成几个合理的独立档案,什么时候需要分,怎么才能分的好。然后将会告诉你 GNU Make 怎样使你的编译和连接步骤自动化。 对于其它 Make 工具的用户来说,虽然在用其它类似工具时要做适当的调整,本文的内 容仍然是非常有用的。如果对你自己的编程工具有怀疑,可以实际的试一试,但请先阅 读用户手册。
1) 多文件项目
1.1为什么使用它们?
首先,多文件项目的好处在那里呢?
它们看起来把事情弄的复杂无比。又要 header 文件,又要 extern 声明,而且如果需要查找一个文件,你要在更多的文件里搜索。 但其实我们有很有力的理由支持我们把一个项目分解成小块。当你改动一行代码,编译 器需要全部重新编译来生成一个新的可执行文件。但如果你的项目是分开在几个小文件里,当你改动其中一个文件的时候,别的源文件的目标文件(object files)已经存在,所以没有什么原因去重新编译它们。你所需要做的只是重现编译被改动过的那个文件,然后重新连接所有的目标文件罢了。在大型的项目中,这意味着从很长的(几分钟到几小时)重新编译缩短为十几,二十几秒的简单调整。只要通过基本的规划,将一个项目分解成多个小文件可使你更加容易的找到一段代码。 很简单,你根据代码的作用把你的代码分解到不同的文件里。当你要看一段代码时,你可以准确的知道在那个文件中去寻找它。 从很多目标文件生成一个程序包 (Library)比从一个单一的大目标文件生成要好的多。 当然实际上这是否真是一个优势则是由你所用的系统来决定的。但是当使用 gcc/ld (一个 GNU C 编译/连接器) 把一个程序包连接到一个程序时,在连接的过程中,它会 尝试不去连接没有使用到的部分。但它每次只能从程序包中把一个完整的目标文件排除在外。因此如果你参考一个程序包中某一个目标档中任何一个符号的话,那么这个目标 文件整个都会被连接进来。要是一个程序包被非常充分的分解了的话,那么经连接后, 得到的可执行文件会比从一个大目标文件组成的程序包连接得到的文件小得多。 又因为你的程序是很模块化的,文件之间的共享部分被减到最少,那就有很多好处—— 可以很容易的追踪到臭虫,这些模块经常是可以用在其它的项目里的,同时别人也可以 更容易的理解你的一段代码是干 什么的。当然此外还有许多别的好处……
1.2 何时分解你的项目
很明显,把任何东西都分解是不合理的。象“世界,你们好”这样的简单程序根本就不能分,因为实在也没什么可分的。把用于测试用的小程序分解也是没什么意思的。但一 般来说,当分解项目有助于布局、发展和易读性的时候,我都会采取它。在大多数的情 况下,这都是适用的。(所谓“世界,你们好”,既 'hello world' ,只是一个介绍 一种编程语言时惯用的范例程序,它会在屏幕上显示一行 'hello world' 。是最简单 的程序。)如果你需要开发一个相当大的项目,在开始前,应该考虑一下你将如何实现它,并且生 成几个文件(用适当的名字)来放你的代码。当然,在你的项目开发的过程中,你可以 建立新的文件,但如果你这么做的话,说明你可能改变了当初的想法,你应该想想是否 需要对整体结构也进行相应的调整。 对于中型的项目,你当然也可以采用上述技巧,但你也可以就那么开始输入你的代码, 当你的码多到难以管理的时候再把它们分解成不同的档案。但以我的经验来说,开始时 在脑子里形成一个大概的方案,并且尽量遵从它,或在开发过程中,随着程序的需要而 修改,会使开发变得更加容易。
1.3 怎样分解项目
先说明,这完全是我个人的意见,你可以(也许你真的会?)用别的方式来做。这会触 动到有关编码风格的问题,而大家从来就没有停止过在这个问题上的争论。在这里我只是给出我自己喜欢的做法(同时也给出这么做的原因):
i) 不要用一个 header 文件指向多个源码文件(例外:程序包 的 header 文件)。用一个 header定义一个源码文件的方式 会更有效,也更容易查寻。否则改变一个源文件的结构(并且 它的 header 文件)就必须重新编译好几个文件。
ii) 如果可以的话,完全可以用超过一个的 header 文件来指向同 一个源码文件。有时将不可公开调用的函数原型,类型定义 等等,从它们的C源码文件中分离出来是非常有用的。使用一 个 header 文件装公开符号,用另一个装私人符号意味着如果 你改变了这个源码文件的内部结构,你可以只是重新编译它而 不需要重新编译那些使用它的公开 header 文件的其它的源文 件。
iii) 不要在多个 header 文件中重复定义信息。 如果需要, 在其中一个 header 文件里 #include 另一个,但 是不要重复输入相同的 header 信息两次。原因是如果你 以后改 变了这个信息,你只需要把它改变一次,不用搜索并改变另外一 个重复的信 息。
iv) 在每一个源码文件里, #include 那些声明了源码文件中的符 号的所有 header 文件。这样一来,你在源码文件和 header 文件对某些函数做出的矛盾声明可以比较容易的被编译器发现。
1.4 对于常见错误的注释
a) 定义符 (Identifier) 在源码文件中的矛盾:在C里,变量和函数的缺 省状态是公用的。因此,任何C源码档案都可以引用存在于其它源 码档中的通用 (global) 函数和通用变量,既使这个档案没有那个变 量或函数的声明或原型。因此你必须保证在不 同的两个档案里不能 用同一个符号名称,否则会有连接错误或者在编译时会有警告。 一种避免这种错误的方法是在公用的符号前加上跟其所在源文件有 关的前缀。比如:
所有在 gfx.c 里的函数都加上前缀“gfx_”。如果 你很小心的分解你的程序,使用有 意义的函数名称,并且不是过分 使用通用变量,当然这根本就不是问题。 要防止一个符号在它被定义的源文件以外被看到,可在它的定义前 加上关键字 “static”。这对只在一个档案内部使用,其它档案都 都不会用到的简单函数是很有用的。
b) 多次定义的符号: header 档会被逐字的替换到你源文件里 #include 的位置的。 因此,如果 header 档被 #include 到一个以上的源文件 里,这个 header 档中所有 的定义就会出现在每一个有关的源码文件 里。这会使它们里的符号被定义一次以上, 从而出现连接错误(见 上)。
解决方法: 不要在 header 档里定义变量。你只需要在 header 档里声明它们然后在 适当的C源码文件(应该 #include 那个 header 档的那个)里定义它们(一次)。对于初学者来说,定义和声明是 很容易混淆的。声明的作用是告诉编译器其所声明的符 号应该存在, 并且要有所指定的类型。但是,它并不会使编译器分配贮存空间。 而定 义的做用是要求编译器分配贮存空间。当做一个声明而不是做 定义的时候,在声明前放一个关键字“extern”。 例如,我们有一个叫“counter”的变量,如果想让它成为公用的, 我们在一个源码程 序(只在一个里面)的开始定义它:“int counter;”,再在相关的 header 档里声明 它:“extern int counter;”。 函数原型里隐含着 extern 的意思,所以不需顾虑这个问题。
c) 重复定义,重复声明,矛盾类型:
请考虑如果在一个C源码文件中 #include 两个档 a.h 和 b.h, 而 a.h 又 #include 了 b.h 档(原因是 b.h 档定义了一些 a.h 需要的类型),会发生什么事呢?这时该 C源码文件 #include 了 b.h 两次。因此每一个在 b.h 中的 #define 都发生了两 次,每一 个声明发生了两次,等等。理论上,因为它们是完全一样的拷贝, 所以应该 不会有什么问题,但在实际应用上,这是不符合C的语法 的,可能在编译时出现错误,或至少是警告。 解决的方法是要确定每一个 header 档在任一个源码文件中只被包 含了一次。我们一 般是用预处理器来达到这个目的的。当我们进入 每一个 header 档时,我们为这个 header 档 #define 一个巨集 指令。只有在这个巨集指令没有被定义的前提下,我们 才真正使用 该 header 档的主体。在实际应用上,我们只要简单的把下面一段 码放在 每一个 header 档的开始部分:
#ifndef FILENAME_H
#define FILENAME_H
然后把下面一行码放在最后:
#endif
用 header 档的档名(大写的)代替上面的 FILENAME_H,用底线 代替档名中的点。有些人喜欢在 #endif 加上注释来提醒他们这个 #endif 指的是什么。例如:
#endif /* #ifndef FILENAME_H */
我个人没有这个习惯,因为这其实是很明显的。当然这只是各人的 风格不同,无伤大雅。
你只需要在那些有编译错误的 header 档中加入这个技巧,但在所 有的 header 档中都加入也没什么损失,到底这是个好习惯。
1.5 重新编译一个多文件项目
清楚的区别编译和连接是很重要的。编译器使用源码文件来产生某种 形式的目标文件 (object files)。在这个过程中,外部的符号参考并 没有被解释或替换。然后我们使用连接器来连接这些目标文件和一些 标准的程序包再加你指定的程序包,最后连接生 成一个可执行程序。 在这个阶段,一个目标文件中对别的文件中的符号的参考被解释,并 报告不能被解释的参考,一般是以错误信息的形式报告出来。 基本的步骤就应该是,把你的源码文件一个一个的编译成目标文件的格 式,最后把所 有的目标文件加上需要的程序包连接成一个可执行文件。 具体怎么做是由你的编译器 决定的。这里我只给出 gcc (GNU C 编译 器)的有关命令,这些有可能对你的非 gcc 编译器也适用。
gcc 是一个多目标的工具。它在需要的时候呼叫其它的元件(预处理 程序,编译器,
组合程序,连接器)。具体的哪些元件被呼叫取决于 输入文件的类型和你传递给它的 开关。 一般来说,如果你只给它C源码文件,它将预处理,编译,组合所有 的文件,然后把 所得的目标文件连接成一个可执行文件(一般生成的 文件被命名为 a.out )。你当然 可以这么做,但这会破坏很多我们 把一个项目分解成多个文件所得到的好处。 如果你给它一个 -c 开关,gcc 只把给它的文件编译成目标文件, 用源码文件的文件 名命名但把其后缀由“.c”或“.cc”变成“.o”。 如果你给它的是一列目标文件, gcc 会把它们连接成可执行文件, 缺省文件名是 a.out 。你可以改变缺省名,用开 -o 后跟你指定 的文件名。因此,当你改变了一个源码文件后,你需要重新编译它: 'gcc -c filename.c' 然后 重新连接你的项目: 'gcc -o exec_filename *.o'。 如果你改变了一个 header 档, 你需要重新编译所有 #include 过 这个档的源码文件,你可以用 'gcc -c file1.c file2.c file3.c' 然后象上边一样连接。 当然这么做是很繁琐的,幸亏我们有些工具使这个步骤变得简单。 本文的第二部分就 是介绍其中的一件工具:GNU Make 工具。
2) GNU Make 工具
2.1 基本 makefile 结构
GNU Make 的主要工作是读进一个文本文件, makefile 。这个文 件里主要是有关哪些 文件(‘target’目的文件)是从哪些别的 文件(‘dependencies’依靠文件)中产 生的,用什么命令来进行 这个产生过程。有了这些信息, make 会检查磁碟上的文件,如果 目的文件的时间戳(该文件生成或被改动时的时间)比至少它的一 个依靠文件旧的话, make 就执行相应的命令,以便更新目的文件。 (目的文件不一定是最后的可执行档,它可以是任何一个文件。) makefile 一般被叫做“makefile”或“Makefile”。当然你可以 在 make 的命令行指 定别的文件名。如果你不特别指定,它会寻 找“makefile”或“Makefile”,因此使用这两个名字是最简单 的。
一个 makefile 主要含有一系列的规则,如下:
例如,考虑以下的 makefile :
=== makefile 开始 ===
myprog : foo.o bar.o
gcc foo.o bar.o -o myprog
foo.o : foo.c foo.h bar.h
gcc -c foo.c -o foo.o
bar.o : bar.c bar.h
gcc -c bar.c -o bar.o
=== makefile 结束 ===
这是一个非常基本的 makefile —— make 从最上面开始,把上 面第一个目的, ‘myprog’,做为它的主要目标(一个它需要保 证其总是最新的最终目标)。给出的 规则说明只要文件‘myprog’ 比文件‘foo.o’或‘bar.o’中的任何一个旧,下一行的命令将 会被执行。但是,在检查文件 foo.o 和 bar.o 的时间戳之前,它会往下查 找那些把 foo.o 或 bar.o 做为目标文件的规则。它找到的关于 foo.o 的规则,该文件的依靠文件是 foo.c, foo.h 和 bar.h 。 它从下面再找不到生成这些依靠文件的规则,它就开始检 查磁碟 上这些依靠文件的时间戳。如果这些文件中任何一个的时间戳比 foo.o 的新, 命令 'gcc -o foo.o foo.c' 将会执行,从而更新 文件 foo.o 。 接下来对文件 bar.o 做类似的检查,依靠文件在这里是文件 bar.c 和 bar.h 。 现在, make 回到‘myprog’的规则。如果刚才两个规则中的任 何一个被执行, myprog 就需要重建(因为其中一个 .o 档就会比 ‘myprog’新),因此连接命令将被 执行。
希望到此,你可以看出使用 make 工具来建立程序的好处——前 一章中所有繁琐的检 查步骤都由 make 替你做了:检查时间戳。 你的源码文件里一个简单改变都会造成那 个文件被重新编译(因 为 .o 文件依靠 .c 文件),进而可执行文件被重新连接(因 为 .o 文件被改变了)。其实真正的得益是在当你改变一个 header 档的时候——你不 再需要记住那个源码文件依靠它,因为所有的 资料都在 makefile 里。 make 会很轻 松的替你重新编译所有那 些因依靠这个 header 文件而改变了的源码文件,如有需 要,再 进行重新连接。 当然,你要确定你在 makefile 中所写的规则是正确无误的,只 列出那些在源码文件 中被 #include 的 header 档……
2.2 编写 make 规则 (Rules)
最明显的(也是最简单的)编写规则的方法是一个一个的查 看源码文件,把它们的目标文件做为目的,而C源码文件和被它 #include 的 header 档做为依靠文件。但是你 也要把其它被这些 header 档 #include 的 header 档也列为依靠文件,还有那些被包括的文件所包括的文件……然后你会发现要对越来越多的文件 进行管理,然后你的头发开始脱落,你的脾气开始变坏,你的脸 色变成菜色,你走在路上开始跟电线杆子 碰撞,终于你捣毁你的 电脑显示器,停止编程。到低有没有些容易点儿的方法呢? 当然有!向编译器要!在编译每一个源码文件的时候,它实在应 该知道应该包括什么样的 header 档。使用 gcc 的时候,用 -M 开关,它会为每一个你给它的C文件输出一个规则,把目标文件 做为目的,而这个C文件和所有应该被 #include 的 header 文 件将做为依靠文件。注意这个规则会加入所有 header 文件,包 括被角括号(`<', `>;')和双引号(`"')所包围的文件。其实我们可以 相当肯定系统 header 档(比如 stdio.h, stdlib.h 等等)不会 被我们更改,如果你用 -MM 来代替 -M 传递给 gcc, 那些用角括 号包围的 header 档将不会被包括。(这会节省一些编译时间) 由 gcc 输出的规则不会含有命令部分;你可以自己写入你的命令 或者什么也不写,而 让 make 使用它的隐含的规则(参考下面的 2.4 节)。
2.3 Makefile 变量
上面提到 makefiles 里主要包含一些规则。它们包含的其它的东 西是变量定义。 makefile 里的变量就像一个环境变量(environment variable)。 事实上,环境变量在 make 过程中被解释成 make 的变量。这些 变量是大小写敏感的,一般使用大写字母。 它们可以从几乎任何 地方被引用,也可以被用来做很多事情,比如:
i) 贮存一个文件名列表。在上面的例子里,生成可执行文件的 规则包含一些目标文件 名做为依靠。在这个规则的命令行 里同样的那些文件被输送给 gcc 做为命令参数。如果在这 里使用一个变数来贮存所有的目标文件名,加入新的目标 文件会变的简单而且
较不易出错。
ii) 贮存可执行文件名。如果你的项目被用在一个非 gcc 的系 统里,或者如果你想使用一个不同的编译器,你必须将所 有使用编译器的地方改成用新的编译器名。但是如 果使用一 个变量来代替编译器名,那么你只需要改变一个地方,其 它所有地方的命令名就都改变了。
iii) 贮存编译器旗标。假设你想给你所有的编译命令传递一组 相同的选项(例 -Wall -O -g);如果你把这组选项存 入一个变量,那么你可以把这个变量放在所有 呼叫编译器 的地方。而当你要改变选项的时候,你只需在一个地方改 变这个变量的内 容。要设定一个变量,你只要在一行的开始写下这个变量的名字,后 面跟一个 = 号,后面 跟你要设定的这个变量的值。以后你要引用 这个变量,写一个 $ 符号,后面是围在括 号里的变量名。比如在 下面,我们把前面的 makefile 利用变量重写一遍:
=== makefile 开始 ===
OBjs = foo.o bar.o
CC = gcc
CFLAGS = -Wall -O -g
myprog : $(OBjs)
$(CC) $(OBjs) -o myprog
foo.o : foo.c foo.h bar.h
$(CC) $(CFLAGS) -c foo.c -o foo.o
bar.o : bar.c bar.h
$(CC) $(CFLAGS) -c bar.c -o bar.o
=== makefile 结束 ===
还有一些设定好的内部变量,它们根据每一个规则内容定义。三个 比较有用的变量是$@, $< 和 $^ (这些变量不需要括号括住)。 $@ 扩展成当前规则的目的文件名, $< 扩展成依靠列表中的第 一个依靠文件,而 $^ 扩展成整个依靠的列表(除掉了里面所有重 复的文件名)。利用这些变量,我们可以把上面的 makefile 写成:
=== makefile 开始 ===
OBjs = foo.o bar.o
CC = gcc
CFLAGS = -Wall -O -g
myprog : $(OBjs)
$(CC) $^ -o $@
foo.o : foo.c foo.h bar.h
$(CC) $(CFLAGS) -c $< -o $@
bar.o : bar.c bar.h
$(CC) $(CFLAGS) -c $< -o $@
=== makefile 结束 ===
你可以用变量做许多其它的事情,特别是当你把它们和函数混合 使用的时候。如果需 要更进一步的了解,请参考 GNU Make 手册。 ('man make', 'man makefile')
2.4 隐含规则 (Implicit Rules)
请注意,在上面的例子里,几个产生 .o 文件的命令都是一样的。 都是从 .c 文件和 相关文件里产生 .o 文件,这是一个标准的步 骤。其实 make 已经知道怎么做——它 有一些叫做隐含规则的内 置的规则,这些规则告诉它当你没有给出某些命令的时候, 应该 怎么办。如果你把生成 foo.o 和 bar.o 的命令从它们的规则中删除, make 将会查找它的隐含 规则,然后会找到一个适当的命令。它的命令会 使用一些变量,因此你可以按照你的 想法来设定它:它使用变量 CC 做为编译器(象我们在前面的例子),并且传递变量 CFLAGS (给 C 编译器,C++ 编译器用 CXXFLAGS ),CPPFLAGS ( C 预 处理器旗 标), TARGET_ARCH (现在不用考虑这个),然后它加 入旗标 '-c' ,后面跟变量 $< (第一个依靠名),然后是旗 标 '-o' 跟变量 $@ (目的文件名)。
一个C编译的 具体命令将 会是:$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ 当然你可以按照你自己的需要来定义这些变量。这就是为什么用 gcc 的 -M 或 -MM 开 关输出的码可以直接用在一个 makefile 里。 2.5 假象目的 (Phony Targets) 假设你的一个项目最后需要产生两个可执行文件。你的主要目标 是产生两个可执行文 件,但这两个文件是相互独立的——如果一 个文件需要重建,并不影响另一个。你可 以使用“假象目的”来 达到这种效果。一个假象目的跟一个正常的目的几乎是一样 的, 只是这个目的文件是不存在的。因此, make 总是会假设它需要 被生成,当把它 的依赖文件更新后,就会执行它的规则里的命令 行。 如果在我们的 makefile 开始处输入:
all : exec1 exec2 其中 exec1 和 exec2 是我们做为目的的两个可执行文件。 make 把这个 'all' 做为 它的主要目的,每次执行时都会尝试把 'all' 更新。但既然这行规则里没有哪个命令 来作用在一个叫 'all' 的 实际文件(事实上 all 并不会在磁碟上实际产生),所以 这个规 则并不真的改变 'all' 的状态。可既然这个文件并不存在,所以 make 会尝试 更新 all 规则,因此就检查它的依靠 exec1, exec2 是否需要更新,如果需要,就把 它们更新,从而达到我们的目的。 假象目的也可以用来描述一组非预设的动作。例如,你想把所有由 make 产生的文件删 除,你可以在 makefile 里设立这样一个规则:
veryclean :
rm *.o
rm myprog
前提是没有其它的规则依靠这个 'veryclean' 目的,它将永远 不会被执行。但是,如果你明确的使用命令 'make veryclean' , make 会把这个目的做为它的主要目标,执行那些 rm 命令。如果你的磁碟上存在一个叫 veryclean 文件,会发生什么事?这 时因为在这个规则里 没有任何依靠文件,所以这个目的文件一定是 最新的了(所有的依靠文件都已经是最 新的了),所以既使用户明 确命令 make 重新产生它,也不会有任何事情发生。解决 方法是标 明所有的假象目的(用 .PHONY),这就告诉 make 不用检查它们 是否存在 于磁碟上,也不用查找任何隐含规则,直接假设指定的目 的需要被更新。在 makefile 里加入下面这行包含上面规则的规则:
..PHONY : veryclean
就可以了。注意,这是一个特殊的 make 规则,make 知道 .PHONY 是一个特殊目的, 当然你可以在它的依靠里加入你想用的任何假象 目的,而 make 知道它们都是假象目 的。
2.6 函数 (Functions)
makefile 里的函数跟它的变量很相似——使用的时候,你用一个 $ 符号跟开括号,函 数名,空格后跟一列由逗号分隔的参数,最后 用关括号结束。例如,在 GNU Make 里 有一个叫 'wildcard' 的函 数,它有一个参数,功能是展开成一列所有符合由其参数 描述的文 件名,文件间以空格间隔。你可以像下面所示使用这个命令:
SOURCES = $(wildcard *.c)
这行会产生一个所有以 '.c' 结尾的文件的列表,然后存入变量 SOURCES 里。当然你不需要一定要把结果存入一个变量。
另一个有用的函数是 patsubst ( patten substitude, 匹配替 换的缩写)函数。它 需要3个参数——第一个是一个需要匹配的 式样,第二个表示用什么来替换它,第三 个是一个需要被处理的 由空格分隔的字列。例如,处理那个经过上面定义后的变量,
OBjs = $(patsubst %.c,%.o,$(SOURCES))
这行将处理所有在 SOURCES 字列中的字(一列文件名),如果它的 结尾是 '.c' ,就 用 '.o' 把 '.c' 取代。注意这里的 % 符号将匹 配一个或多个字符,而它每次所匹配 的字串叫做一个‘柄’(stem) 。 在第二个参数里, % 被解读成用第一参数所匹配的 那个柄。
2.7 一个比较有效的 makefile
利用我们现在所学的,我们可以建立一个相当有效的 makefile 。 这个 makefile 可 以完成大部分我们需要的依靠检查,不用做太大 的改变就可直接用在大多数的项目里。
首先我们需要一个基本的 makefile 来建我们的程序。我们可以让 它搜索当前目录,找到源码文件,并且假设它们都是属于我们的项 目的,放进一个叫 SOURCES 的变量。 这里如果也包含所有的 *.cc 文件,也许会更保险,因为源码文件可能是 C++ 码的。 SOURCES = $(wildcard *.c *.cc) 利用 patsubst ,我们可以由源码文件名产生目标文件名,我们需 要编译出这些目标 文件。如果我们的源码文件既有 .c 文件,也有 .cc 文件,我们需要使用相嵌的 patsubst 函数呼叫:
OBjs = $(patsubst %.c,%.o,$(patsubst %.cc,%.o,$(SOURCES)))
最里面一层 patsubst 的呼叫会对 .cc 文件进行后缀替代,产生的结 果被外层的 patsubst 呼叫处理,进行对 .c 文件后缀的替代。
现在我们可以设立一个规则来建可执行文件:
myprog : $(OBjs)
gcc -o myprog $(OBjs)
进一步的规则不一定需要, gcc 已经知道怎么去生成目标文件 (object files) 。下面我们可以设定产生依靠信息的规则:
depends : $(SOURCES)
gcc -M $(SOURCES) >; depends
在这里如果一个叫 'depends' 的文件不存在,或任何一个源码文件 比一个已存在的 depends 文件新,那么一个 depends 文件会被生 成。depends 文件将会含有由 gcc 产生的关于源码文件的规则(注 意 -M 开关)。现在我们要让 make 把这些规则当做 makefile 档 的一部分。这里使用的技巧很像 C 语言中的 #include 系统——我 们要 求 make 把这个文件 include 到 makefile 里,如下:
include depends
GNU Make 看到这个,检查 'depends' 目的是否更新了,如果没有, 它用我们给它的命令重新产生 depends 档。然后它会把这组(新) 规则包含进来,继续处理最终目标 'myprog' 。当看到有关 myprog 的规则,它会检查所有的目标文件是否更新——利用 depends 文件 里的规则,当然这些规则现在已经是更新过的了。
这个系统其实效率很低,因为每当一个源码文件被改动,所有的源码 文件都要被预处 理以产生一个新的 'depends' 文件。而且它也不是 100% 的安全,这是因为当一个 header 档被改动,依靠信息并不会 被更新。但就基本工作来说,它也算相当有用的 了。
2.8 一个更好的 makefile
这是一个我为我大多数项目设计的 makefile 。它应该可以不需要修 改的用在大部分项目里。我主要把它用在 djgpp 上,那是一个 DOS 版的 gcc 编译器。因此你可以看到执行的命令名、 'alleg' 程序包、 和 RM -F 变量都反映了这一点。
=== makefile 开始 ===
######################################
#
# Generic makefile
#
# by George Foot
# email: george.foot@merton.ox.ac.uk
#
# Copyright (c) 1997 George Foot
# All rights reserved.
# 保留所有版权
#
# No warranty, no liability;
# you use this at your own risk.
# 没保险,不负责
# 你要用这个,你自己担风险
#
# You are free to modify and
# distribute this without giving
# credit to the original author.
# 你可以随便更改和散发这个文件
# 而不需要给原作者什么荣誉。
# (你好意思?)
#
######################################
### Customising
# 用户设定
#
# Adjust the following if necessary; EXECUTABLE is the target
# executable's filename, and LIBS is a list of libraries to link in
# (e.g. alleg, stdcx, iostr, etc). You can override these on make's
# command line of course, if you prefer to do it that way.
#
# 如果需要,调整下面的东西。 EXECUTABLE 是目标的可执行文件名, LIBS
# 是一个需要连接的程序包列表(例如 alleg, stdcx, iostr 等等)。当然你
# 可以在 make 的命令行覆盖它们,你愿意就没问题。
#
EXECUTABLE := mushroom.exe
LIBS := alleg
# Now alter any implicit rules' variables if you like, e.g.:
#
# 现在来改变任何你想改动的隐含规则中的变量,例如
CFLAGS := -g -Wall -O3 -m486
CXXFLAGS := $(CFLAGS)
# The next bit checks to see whether rm is in your djgpp bin
# directory; if not it uses del instead, but this can cause (harmless)
# `File not found' error messages. If you are not using DOS at all,
# set the variable to something which will unquestioningly remove
# files.
#
# 下面先检查你的 djgpp 命令目录下有没有 rm 命令,如果没有,我们使用 del 命令来代替,但有可能给我们 'File not found' 这个错误信息,这没 # 什么大碍。如果你不是用 DOS ,把它设定成一个删文件而不废话的命令。 (其实这一步在 UNIX 类的系统上是多余的,只是方便 DOS 用户。 UNIX 用户可以删除这5行命令。)
ifneq ($(wildcard $(DJDIR)/bin/rm.exe),)
RM-F := rm -f
else
RM-F := del
endif
# You shouldn't need to change anything below this point.
#
# 从这里开始,你应该不需要改动任何东西。(我是不太相信,太NB了!)
SOURCE := $(wildcard *.c) $(wildcard *.cc)
OBjs := $(patsubst %.c,%.o,$(patsubst %.cc,%.o,$(SOURCE)))
DEPS := $(patsubst %.o,%.d,$(OBjs))
MISSING_DEPS := $(filter-out $(wildcard $(DEPS)),$(DEPS))
MISSING_DEPS_SOURCES := $(wildcard $(patsubst %.d,%.c,$(MISSING_DEPS)) \
$(patsubst %.d,%.cc,$(MISSING_DEPS)))
CPPFLAGS += -MD
..PHONY : everything deps objs clean veryclean rebuild
everything : $(EXECUTABLE)
deps : $(DEPS)
objs : $(OBjs)
clean :
@$(RM-F) *.o
@$(RM-F) *.d
veryclean: clean
@$(RM-F) $(EXECUTABLE)
rebuild: veryclean everything
ifneq ($(MISSING_DEPS),)
$(MISSING_DEPS) :
@$(RM-F) $(patsubst %.d,%.o,$@)
endif
-include $(DEPS)
$(EXECUTABLE) : $(OBjs)
gcc -o $(EXECUTABLE) $(OBjs) $(addprefix -l,$(LIBS))
=== makefile 结束 ===
有几个地方值得解释一下的。首先,我在定义大部分变量的时候使 用的是 := 而不是
= 符号。它的作用是立即把定义中参考到的函 数和变量都展开了。如果使用 = 的话,
函数和变量参考会留在那 儿,就是说改变一个变量的值会导致其它变量的值也被改
变。例 如:
A = foo
B = $(A)
# 现在 B 是 $(A) ,而 $(A) 是 'foo' 。
A = bar
# 现在 B 仍然是 $(A) ,但它的值已随着变成 'bar' 了。
B := $(A)
# 现在 B 的值是 'bar' 。
A = foo
# B 的值仍然是 'bar' 。
make 会忽略在 # 符号后面直到那一行结束的所有文字。
ifneg...else...endif 系统是 makefile 里让某一部分码有条件的 失效/有效的工
具。 ifeq 使用两个参数,如果它们相同,它把直 到 else (或者 endif ,如果没有
else 的话)的一段码加进 makefile 里;如果不同,把 else 到 endif 间的一段码加入 makefile (如果有 else )。 ifneq 的用法刚好相反。 'filter-out' 函数使用两个用空格分开的列表,它把第二列表中所 有的存在于第一列 表中的项目删除。我用它来处理 DEPS 列表,把所 有已经存在的项目都删除,而只保留缺少的那些。
我前面说过, CPPFLAGS 存有用于隐含规则中传给预处理器的一些 旗标。而 -MD 开关 类似 -M 开关,但是从源码文件 .c 或 .cc 中 形成的文件名是使用后缀 .d 的(这就 解释了我形成 DEPS 变量的 步骤)。DEPS 里提到的文件后来用 '-include' 加进了 makefile 里,它隐藏了所有因文件不存在而产生的错误信息。 如果任何依靠文件不存在, makefile 会把相应的 .o 文件从磁碟 上删除,从而使得 make 重建它。因为 CPPFLAGS 指定了 -MD , 它的 .d 文件也被重新产生。 最后, 'addprefix' 函数把第二个参数列表的每一项前缀上第一 个参数值。 这个 makefile 的那些目的是(这些目的可以传给 make 的命令行 来直接选用):
everything:(预设) 更新主要的可执行程序,并且为每一个 源码文件生成或更新一个 '.d' 文件和一个 '.o' 文件。 deps: 只是为每一个源码程序产生或更新一个 '.d' 文件。 objs: 为每一个源码程序生成或更新 '.d' 文件和目标文件。 clean: 删除所有中介/依靠文件( *.d 和 *.o )。
veryclean: 做 `clean' 和删除可执行文件。
rebuild: 先做 `veryclean' 然后 `everything' ;既完全重建。
除了预设的 everything 以外,这里头只有 clean , veryclean , 和 rebuild 对用户是有意义的。 我还没有发现当给出一个源码文件的目录,这个 makefile 会失败的 情况,除非依靠 文件被弄乱。如果这种弄乱的情况发生了,只要输入 `make clean' ,所有的目标文件和依靠文件会被删除,问题就应该 被解决了。当然,最好不要把它们弄乱。如果你发现在某种情况下这 个 makefile 文件不能完成它的工作,请告诉我,我会把它整好的。
3 总结
我希望这篇文章足够详细的解释了多文件项目是怎么运作的,也说明了 怎样安全而合理的使用它。到此,你应该可以轻松的利用 GNU Make 工 具来管理小型的项目,如果 你完全理解了后面几个部分的话,这些对于 你来说应该没什么困难。 GNU Make 是一件强大的工具,虽然它主要是用来建立程序,它还有很多 别的用处。如果想要知道更多有关这个工具的知识,它的句法,函数, 和许多别的特点,你应该参
看它的参考文件 (info pages, 别的 GNU 工具也一样,看它们的 info pages. )。
介绍
本文将首先介绍为什么要将你的C源代码分离成几个合理的独立档案,什么时候需要分,怎么才能分的好。然后将会告诉你 GNU Make 怎样使你的编译和连接步骤自动化。 对于其它 Make 工具的用户来说,虽然在用其它类似工具时要做适当的调整,本文的内 容仍然是非常有用的。如果对你自己的编程工具有怀疑,可以实际的试一试,但请先阅 读用户手册。
1) 多文件项目
1.1为什么使用它们?
首先,多文件项目的好处在那里呢?
它们看起来把事情弄的复杂无比。又要 header 文件,又要 extern 声明,而且如果需要查找一个文件,你要在更多的文件里搜索。 但其实我们有很有力的理由支持我们把一个项目分解成小块。当你改动一行代码,编译 器需要全部重新编译来生成一个新的可执行文件。但如果你的项目是分开在几个小文件里,当你改动其中一个文件的时候,别的源文件的目标文件(object files)已经存在,所以没有什么原因去重新编译它们。你所需要做的只是重现编译被改动过的那个文件,然后重新连接所有的目标文件罢了。在大型的项目中,这意味着从很长的(几分钟到几小时)重新编译缩短为十几,二十几秒的简单调整。只要通过基本的规划,将一个项目分解成多个小文件可使你更加容易的找到一段代码。 很简单,你根据代码的作用把你的代码分解到不同的文件里。当你要看一段代码时,你可以准确的知道在那个文件中去寻找它。 从很多目标文件生成一个程序包 (Library)比从一个单一的大目标文件生成要好的多。 当然实际上这是否真是一个优势则是由你所用的系统来决定的。但是当使用 gcc/ld (一个 GNU C 编译/连接器) 把一个程序包连接到一个程序时,在连接的过程中,它会 尝试不去连接没有使用到的部分。但它每次只能从程序包中把一个完整的目标文件排除在外。因此如果你参考一个程序包中某一个目标档中任何一个符号的话,那么这个目标 文件整个都会被连接进来。要是一个程序包被非常充分的分解了的话,那么经连接后, 得到的可执行文件会比从一个大目标文件组成的程序包连接得到的文件小得多。 又因为你的程序是很模块化的,文件之间的共享部分被减到最少,那就有很多好处—— 可以很容易的追踪到臭虫,这些模块经常是可以用在其它的项目里的,同时别人也可以 更容易的理解你的一段代码是干 什么的。当然此外还有许多别的好处……
1.2 何时分解你的项目
很明显,把任何东西都分解是不合理的。象“世界,你们好”这样的简单程序根本就不能分,因为实在也没什么可分的。把用于测试用的小程序分解也是没什么意思的。但一 般来说,当分解项目有助于布局、发展和易读性的时候,我都会采取它。在大多数的情 况下,这都是适用的。(所谓“世界,你们好”,既 'hello world' ,只是一个介绍 一种编程语言时惯用的范例程序,它会在屏幕上显示一行 'hello world' 。是最简单 的程序。)如果你需要开发一个相当大的项目,在开始前,应该考虑一下你将如何实现它,并且生 成几个文件(用适当的名字)来放你的代码。当然,在你的项目开发的过程中,你可以 建立新的文件,但如果你这么做的话,说明你可能改变了当初的想法,你应该想想是否 需要对整体结构也进行相应的调整。 对于中型的项目,你当然也可以采用上述技巧,但你也可以就那么开始输入你的代码, 当你的码多到难以管理的时候再把它们分解成不同的档案。但以我的经验来说,开始时 在脑子里形成一个大概的方案,并且尽量遵从它,或在开发过程中,随着程序的需要而 修改,会使开发变得更加容易。
1.3 怎样分解项目
先说明,这完全是我个人的意见,你可以(也许你真的会?)用别的方式来做。这会触 动到有关编码风格的问题,而大家从来就没有停止过在这个问题上的争论。在这里我只是给出我自己喜欢的做法(同时也给出这么做的原因):
i) 不要用一个 header 文件指向多个源码文件(例外:程序包 的 header 文件)。用一个 header定义一个源码文件的方式 会更有效,也更容易查寻。否则改变一个源文件的结构(并且 它的 header 文件)就必须重新编译好几个文件。
ii) 如果可以的话,完全可以用超过一个的 header 文件来指向同 一个源码文件。有时将不可公开调用的函数原型,类型定义 等等,从它们的C源码文件中分离出来是非常有用的。使用一 个 header 文件装公开符号,用另一个装私人符号意味着如果 你改变了这个源码文件的内部结构,你可以只是重新编译它而 不需要重新编译那些使用它的公开 header 文件的其它的源文 件。
iii) 不要在多个 header 文件中重复定义信息。 如果需要, 在其中一个 header 文件里 #include 另一个,但 是不要重复输入相同的 header 信息两次。原因是如果你 以后改 变了这个信息,你只需要把它改变一次,不用搜索并改变另外一 个重复的信 息。
iv) 在每一个源码文件里, #include 那些声明了源码文件中的符 号的所有 header 文件。这样一来,你在源码文件和 header 文件对某些函数做出的矛盾声明可以比较容易的被编译器发现。
1.4 对于常见错误的注释
a) 定义符 (Identifier) 在源码文件中的矛盾:在C里,变量和函数的缺 省状态是公用的。因此,任何C源码档案都可以引用存在于其它源 码档中的通用 (global) 函数和通用变量,既使这个档案没有那个变 量或函数的声明或原型。因此你必须保证在不 同的两个档案里不能 用同一个符号名称,否则会有连接错误或者在编译时会有警告。 一种避免这种错误的方法是在公用的符号前加上跟其所在源文件有 关的前缀。比如:
所有在 gfx.c 里的函数都加上前缀“gfx_”。如果 你很小心的分解你的程序,使用有 意义的函数名称,并且不是过分 使用通用变量,当然这根本就不是问题。 要防止一个符号在它被定义的源文件以外被看到,可在它的定义前 加上关键字 “static”。这对只在一个档案内部使用,其它档案都 都不会用到的简单函数是很有用的。
b) 多次定义的符号: header 档会被逐字的替换到你源文件里 #include 的位置的。 因此,如果 header 档被 #include 到一个以上的源文件 里,这个 header 档中所有 的定义就会出现在每一个有关的源码文件 里。这会使它们里的符号被定义一次以上, 从而出现连接错误(见 上)。
解决方法: 不要在 header 档里定义变量。你只需要在 header 档里声明它们然后在 适当的C源码文件(应该 #include 那个 header 档的那个)里定义它们(一次)。对于初学者来说,定义和声明是 很容易混淆的。声明的作用是告诉编译器其所声明的符 号应该存在, 并且要有所指定的类型。但是,它并不会使编译器分配贮存空间。 而定 义的做用是要求编译器分配贮存空间。当做一个声明而不是做 定义的时候,在声明前放一个关键字“extern”。 例如,我们有一个叫“counter”的变量,如果想让它成为公用的, 我们在一个源码程 序(只在一个里面)的开始定义它:“int counter;”,再在相关的 header 档里声明 它:“extern int counter;”。 函数原型里隐含着 extern 的意思,所以不需顾虑这个问题。
c) 重复定义,重复声明,矛盾类型:
请考虑如果在一个C源码文件中 #include 两个档 a.h 和 b.h, 而 a.h 又 #include 了 b.h 档(原因是 b.h 档定义了一些 a.h 需要的类型),会发生什么事呢?这时该 C源码文件 #include 了 b.h 两次。因此每一个在 b.h 中的 #define 都发生了两 次,每一 个声明发生了两次,等等。理论上,因为它们是完全一样的拷贝, 所以应该 不会有什么问题,但在实际应用上,这是不符合C的语法 的,可能在编译时出现错误,或至少是警告。 解决的方法是要确定每一个 header 档在任一个源码文件中只被包 含了一次。我们一 般是用预处理器来达到这个目的的。当我们进入 每一个 header 档时,我们为这个 header 档 #define 一个巨集 指令。只有在这个巨集指令没有被定义的前提下,我们 才真正使用 该 header 档的主体。在实际应用上,我们只要简单的把下面一段 码放在 每一个 header 档的开始部分:
#ifndef FILENAME_H
#define FILENAME_H
然后把下面一行码放在最后:
#endif
用 header 档的档名(大写的)代替上面的 FILENAME_H,用底线 代替档名中的点。有些人喜欢在 #endif 加上注释来提醒他们这个 #endif 指的是什么。例如:
#endif /* #ifndef FILENAME_H */
我个人没有这个习惯,因为这其实是很明显的。当然这只是各人的 风格不同,无伤大雅。
你只需要在那些有编译错误的 header 档中加入这个技巧,但在所 有的 header 档中都加入也没什么损失,到底这是个好习惯。
1.5 重新编译一个多文件项目
清楚的区别编译和连接是很重要的。编译器使用源码文件来产生某种 形式的目标文件 (object files)。在这个过程中,外部的符号参考并 没有被解释或替换。然后我们使用连接器来连接这些目标文件和一些 标准的程序包再加你指定的程序包,最后连接生 成一个可执行程序。 在这个阶段,一个目标文件中对别的文件中的符号的参考被解释,并 报告不能被解释的参考,一般是以错误信息的形式报告出来。 基本的步骤就应该是,把你的源码文件一个一个的编译成目标文件的格 式,最后把所 有的目标文件加上需要的程序包连接成一个可执行文件。 具体怎么做是由你的编译器 决定的。这里我只给出 gcc (GNU C 编译 器)的有关命令,这些有可能对你的非 gcc 编译器也适用。
gcc 是一个多目标的工具。它在需要的时候呼叫其它的元件(预处理 程序,编译器,
组合程序,连接器)。具体的哪些元件被呼叫取决于 输入文件的类型和你传递给它的 开关。 一般来说,如果你只给它C源码文件,它将预处理,编译,组合所有 的文件,然后把 所得的目标文件连接成一个可执行文件(一般生成的 文件被命名为 a.out )。你当然 可以这么做,但这会破坏很多我们 把一个项目分解成多个文件所得到的好处。 如果你给它一个 -c 开关,gcc 只把给它的文件编译成目标文件, 用源码文件的文件 名命名但把其后缀由“.c”或“.cc”变成“.o”。 如果你给它的是一列目标文件, gcc 会把它们连接成可执行文件, 缺省文件名是 a.out 。你可以改变缺省名,用开 -o 后跟你指定 的文件名。因此,当你改变了一个源码文件后,你需要重新编译它: 'gcc -c filename.c' 然后 重新连接你的项目: 'gcc -o exec_filename *.o'。 如果你改变了一个 header 档, 你需要重新编译所有 #include 过 这个档的源码文件,你可以用 'gcc -c file1.c file2.c file3.c' 然后象上边一样连接。 当然这么做是很繁琐的,幸亏我们有些工具使这个步骤变得简单。 本文的第二部分就 是介绍其中的一件工具:GNU Make 工具。
2) GNU Make 工具
2.1 基本 makefile 结构
GNU Make 的主要工作是读进一个文本文件, makefile 。这个文 件里主要是有关哪些 文件(‘target’目的文件)是从哪些别的 文件(‘dependencies’依靠文件)中产 生的,用什么命令来进行 这个产生过程。有了这些信息, make 会检查磁碟上的文件,如果 目的文件的时间戳(该文件生成或被改动时的时间)比至少它的一 个依靠文件旧的话, make 就执行相应的命令,以便更新目的文件。 (目的文件不一定是最后的可执行档,它可以是任何一个文件。) makefile 一般被叫做“makefile”或“Makefile”。当然你可以 在 make 的命令行指 定别的文件名。如果你不特别指定,它会寻 找“makefile”或“Makefile”,因此使用这两个名字是最简单 的。
一个 makefile 主要含有一系列的规则,如下:
例如,考虑以下的 makefile :
=== makefile 开始 ===
myprog : foo.o bar.o
gcc foo.o bar.o -o myprog
foo.o : foo.c foo.h bar.h
gcc -c foo.c -o foo.o
bar.o : bar.c bar.h
gcc -c bar.c -o bar.o
=== makefile 结束 ===
这是一个非常基本的 makefile —— make 从最上面开始,把上 面第一个目的, ‘myprog’,做为它的主要目标(一个它需要保 证其总是最新的最终目标)。给出的 规则说明只要文件‘myprog’ 比文件‘foo.o’或‘bar.o’中的任何一个旧,下一行的命令将 会被执行。但是,在检查文件 foo.o 和 bar.o 的时间戳之前,它会往下查 找那些把 foo.o 或 bar.o 做为目标文件的规则。它找到的关于 foo.o 的规则,该文件的依靠文件是 foo.c, foo.h 和 bar.h 。 它从下面再找不到生成这些依靠文件的规则,它就开始检 查磁碟 上这些依靠文件的时间戳。如果这些文件中任何一个的时间戳比 foo.o 的新, 命令 'gcc -o foo.o foo.c' 将会执行,从而更新 文件 foo.o 。 接下来对文件 bar.o 做类似的检查,依靠文件在这里是文件 bar.c 和 bar.h 。 现在, make 回到‘myprog’的规则。如果刚才两个规则中的任 何一个被执行, myprog 就需要重建(因为其中一个 .o 档就会比 ‘myprog’新),因此连接命令将被 执行。
希望到此,你可以看出使用 make 工具来建立程序的好处——前 一章中所有繁琐的检 查步骤都由 make 替你做了:检查时间戳。 你的源码文件里一个简单改变都会造成那 个文件被重新编译(因 为 .o 文件依靠 .c 文件),进而可执行文件被重新连接(因 为 .o 文件被改变了)。其实真正的得益是在当你改变一个 header 档的时候——你不 再需要记住那个源码文件依靠它,因为所有的 资料都在 makefile 里。 make 会很轻 松的替你重新编译所有那 些因依靠这个 header 文件而改变了的源码文件,如有需 要,再 进行重新连接。 当然,你要确定你在 makefile 中所写的规则是正确无误的,只 列出那些在源码文件 中被 #include 的 header 档……
2.2 编写 make 规则 (Rules)
最明显的(也是最简单的)编写规则的方法是一个一个的查 看源码文件,把它们的目标文件做为目的,而C源码文件和被它 #include 的 header 档做为依靠文件。但是你 也要把其它被这些 header 档 #include 的 header 档也列为依靠文件,还有那些被包括的文件所包括的文件……然后你会发现要对越来越多的文件 进行管理,然后你的头发开始脱落,你的脾气开始变坏,你的脸 色变成菜色,你走在路上开始跟电线杆子 碰撞,终于你捣毁你的 电脑显示器,停止编程。到低有没有些容易点儿的方法呢? 当然有!向编译器要!在编译每一个源码文件的时候,它实在应 该知道应该包括什么样的 header 档。使用 gcc 的时候,用 -M 开关,它会为每一个你给它的C文件输出一个规则,把目标文件 做为目的,而这个C文件和所有应该被 #include 的 header 文 件将做为依靠文件。注意这个规则会加入所有 header 文件,包 括被角括号(`<', `>;')和双引号(`"')所包围的文件。其实我们可以 相当肯定系统 header 档(比如 stdio.h, stdlib.h 等等)不会 被我们更改,如果你用 -MM 来代替 -M 传递给 gcc, 那些用角括 号包围的 header 档将不会被包括。(这会节省一些编译时间) 由 gcc 输出的规则不会含有命令部分;你可以自己写入你的命令 或者什么也不写,而 让 make 使用它的隐含的规则(参考下面的 2.4 节)。
2.3 Makefile 变量
上面提到 makefiles 里主要包含一些规则。它们包含的其它的东 西是变量定义。 makefile 里的变量就像一个环境变量(environment variable)。 事实上,环境变量在 make 过程中被解释成 make 的变量。这些 变量是大小写敏感的,一般使用大写字母。 它们可以从几乎任何 地方被引用,也可以被用来做很多事情,比如:
i) 贮存一个文件名列表。在上面的例子里,生成可执行文件的 规则包含一些目标文件 名做为依靠。在这个规则的命令行 里同样的那些文件被输送给 gcc 做为命令参数。如果在这 里使用一个变数来贮存所有的目标文件名,加入新的目标 文件会变的简单而且
较不易出错。
ii) 贮存可执行文件名。如果你的项目被用在一个非 gcc 的系 统里,或者如果你想使用一个不同的编译器,你必须将所 有使用编译器的地方改成用新的编译器名。但是如 果使用一 个变量来代替编译器名,那么你只需要改变一个地方,其 它所有地方的命令名就都改变了。
iii) 贮存编译器旗标。假设你想给你所有的编译命令传递一组 相同的选项(例 -Wall -O -g);如果你把这组选项存 入一个变量,那么你可以把这个变量放在所有 呼叫编译器 的地方。而当你要改变选项的时候,你只需在一个地方改 变这个变量的内 容。要设定一个变量,你只要在一行的开始写下这个变量的名字,后 面跟一个 = 号,后面 跟你要设定的这个变量的值。以后你要引用 这个变量,写一个 $ 符号,后面是围在括 号里的变量名。比如在 下面,我们把前面的 makefile 利用变量重写一遍:
=== makefile 开始 ===
OBjs = foo.o bar.o
CC = gcc
CFLAGS = -Wall -O -g
myprog : $(OBjs)
$(CC) $(OBjs) -o myprog
foo.o : foo.c foo.h bar.h
$(CC) $(CFLAGS) -c foo.c -o foo.o
bar.o : bar.c bar.h
$(CC) $(CFLAGS) -c bar.c -o bar.o
=== makefile 结束 ===
还有一些设定好的内部变量,它们根据每一个规则内容定义。三个 比较有用的变量是$@, $< 和 $^ (这些变量不需要括号括住)。 $@ 扩展成当前规则的目的文件名, $< 扩展成依靠列表中的第 一个依靠文件,而 $^ 扩展成整个依靠的列表(除掉了里面所有重 复的文件名)。利用这些变量,我们可以把上面的 makefile 写成:
=== makefile 开始 ===
OBjs = foo.o bar.o
CC = gcc
CFLAGS = -Wall -O -g
myprog : $(OBjs)
$(CC) $^ -o $@
foo.o : foo.c foo.h bar.h
$(CC) $(CFLAGS) -c $< -o $@
bar.o : bar.c bar.h
$(CC) $(CFLAGS) -c $< -o $@
=== makefile 结束 ===
你可以用变量做许多其它的事情,特别是当你把它们和函数混合 使用的时候。如果需 要更进一步的了解,请参考 GNU Make 手册�/td> |
makefile的一个介绍(网上找的),请高手进来看看是否准确。
呵呵,我最初学习Makefile看的就是这篇文章,我觉得写得非常好!
以后遇上问题都是看www.gun.org上的手册! |
| |