update repository
[cmdllinux.git] / example_n_useful / _makefile_txt / makefile-dependency-generation.html.txt
blobc36254ba6bd8dae8d034e00cc8b70eb8d962b79c
1    Link: canonical
3   current community
5      * chat
6        Code Review
7      * Code Review Meta
9   your communities
11    Sign up or log in to customize your list.
13   more stack exchange communities
15    company blog
16    Stack Exchange Inbox  Reputation and Badges
17    sign up log in tour help 
18      * Tour Start here for a quick overview of the site
19      * Help Center Detailed answers to any questions you might have
20      * Meta Discuss the workings and policies of this site
21      * About Us Learn more about Stack Overflow the company
22      * Business Learn more about hiring developers or posting ads with us
23    _____________________
24    Code Review
25      * Questions
26      * Tags
27      * Users
28      * Badges
29      * Unanswered
30      * Ask Question
31    Link:
32    https://cdn.sstatic.net/Sites/codereview/img/apple-touch-icon.png?v=0a72875519a4
33    _
34    Code Review Stack Exchange is a question and answer site for peer
35    programmer code reviews. Join them; it only takes a minute:
37    Sign up
38    Here's how it works:
39     1. Anybody can ask a question
40     2. Anybody can answer
41     3. The best answers are voted up and rise to the top
43                          makefile dependency generation
45               I need automatic dependency generation to be done in my         
46               makefile. So, I have tried to write one, after googling for     
47               similar ones. I have found some ways to do that, but the        
48               problem is that they are usually too complicated for me         
49               (because of usage of sed command etc. and I want a way for me   
50               to create a makefile without the need of refering to some other 
51               makefile).                                                      
52                                                                               
53               Below is a makefile I hope should do the same job i.e.          
54               automatically find out all the dependencies of the object files 
55               and build them. Could you please review this makefile and point 
56               out cases where the build may fail when it should not have?     
57                                                                               
58               Gpp=g++                                                         
59               srcs=$(wildcard *.cpp)                                          
60               objs=$(srcs:.cpp=.o)                                            
61               deps=$(srcs:.cpp=.d)                                            
62                                                                               
63               default:test                                                    
64                                                                               
65               %.o:%.d                                                         
66                   $(Gpp) -c $*.cpp                                            
67    up vote 15                                                                 
68    down vote  %.d:%.cpp                                                       
69    favorite       echo -n "$*.d ">$*.d                                        
70    3              $(Gpp) -MM $*.cpp>>$*.d                                     
71                                                                               
72               test: $(objs)                                                   
73                   $(Gpp) $^ -o $@                                             
74                                                                               
75               -include $(deps)                                                
76                                                                               
77               .PHONY:clean default                                            
78                                                                               
79               clean:                                                          
80                   -rm -rf *.o test *.d                                        
81                                                                               
82               One place where the makefile fails is when for example a.cpp    
83               initially included a1.h but it has been updated to exclude a1.h 
84               and a1.h file has been deleted from file-system. So, except     
85               that is there any place that this makefile fails?               
86                                                                               
87               c++ makefile                                                    
88                                                                               
89                                         edited Jan 27 '12 asked May 22 '11 at 
90               share|improve this                  at 9:28 10:07               
91               question                              [IMG] [IMG]               
92                                                 palacsint nagavamsikrishna    
93                                               28.5k969152 17614               
94                    You may want to investigate the -MP option. "This option   
95                    instructs CPP to add a phony target for each dependency    
96               5    other than the main file, causing each to depend on        
97                    nothing. These dummy rules work around errors 'make' gives 
98                    if you remove header files without updating the 'Makefile' 
99                    to match." – Charles Bailey May 22 '11 at 12:01            
100                    @Charles Bailey : thanks! that made it even nicer          
101                    – nagavamsikrishna May 22 '11 at 16:58                     
102                                                                               
103               add a comment |  expand to show all comments on this post       
105 3 Answers
107    active oldest votes
109                   Not to be too blunt; but, you're going about this the wrong 
110                   way. Look into the command line option -MMD for GCC,        
111                   specify it when compiling your source; and, retain the      
112                   inclusion statement for dependencies.                       
113                                                                               
114                   Also, no need for a default target. The first target is the 
115                   default target.                                             
116                                                                               
117                   An example:                                                 
118                                                                               
119                   Gpp = g++                                                   
120                   srcs = $(wildcard *.cpp)                                    
121                   objs = $(srcs:.cpp=.o)                                      
122                   deps = $(srcs:.cpp=.d)                                      
123                                                                               
124    up vote 9 down test: $(objs)                                               
125    vote               $(Gpp) $^ -o $@                                         
126                                                                               
127                   %.o: %.cpp                                                  
128                       $(Gpp) -MMD -MP -c $< -o $@                             
129                                                                               
130                   .PHONY: clean                                               
131                                                                               
132                   # $(RM) is rm -f by default                                 
133                   clean:                                                      
134                       $(RM) $(objs) $(deps) test                              
135                                                                               
136                   -include $(deps)                                            
137                                                                               
138                                             answered Apr 23 '12 at 10:05      
139                   share|improve this answer                        [IMG]      
140                                                              Ryan Leckey      
141                                                                    18612      
142                        This is the right way to approach the problem.         
143                        Dependencies are only useful in re-compilation         
144                        (everything gets built the first time through), so you 
145                        don't need to generate the .d files in a separate      
146                        step. – bta Oct 17 '12 at 21:35                        
147                                                                               
148                   add a comment |  expand to show all comments on this post   
150              That will likely generate deps all the time, even if your target 
151              is 'clean'. Put the dep targets and includes in an ifeq block    
152              which checks the makefile target, then there wont be any         
153              dependency generation prior to cleaning (since those files       
154              should be removed by the clean, it is a waste to generate them   
155              prior to clean).                                                 
156                                                                               
157              ifeq ($(MAKECMDGOALS),clean)                                     
158              # doing clean, so dont make deps.                                
159              deps=                                                            
160              else                                                             
161              # doing build, so make deps.                                     
162              deps=$(srcs:.cpp=.d)                                             
163                                                                               
164              %.d:%.cpp                                                        
165                 echo -n "$*.d ">$*.d                                          
166                 $(Gpp) -MM $*.cpp>>$*.d                                       
167                                                                               
168    up vote 6 -include $(deps)                                                 
169    down vote endif # ($(MAKECMDGOALS),clean)                                  
170                                                                               
171              Also it is much cleaner to create subdirs and place the .d and   
172              .o files in the subdirs. Then the source directories (i.e.       
173              'src', ...) remain spotless and the dangerous "-rm -rf *.o test  
174              *.d" is completely avoided.                                      
175                                                                               
176              Also "-rm -rf *.o test *.d" in itself is not optimal. Best to    
177              only remove what is defined, don't remove arbitrary files (and   
178              no need for "-r" either). New code:                              
179                                                                               
180              target=test                                                      
181              rm -f $(objs) $(srcs:.cpp=.d) $(target)                          
182                                                                               
183                                                           answered Jul 20 '11 
184                                        edited Jul 27 '11             at 21:40 
185              share|improve this answer           at 2:24                [IMG] 
186                                                           Jonathan Cline IEEE 
187                                                                          1813 
188                                                                               
189              add a comment |  expand to show all comments on this post        
191      Not exactly what you are asking for but I would suggest using cmake to         
192      generate the Makefile. cmake is good at automatically finding dependencies and 
193      it also lets you build in a separate build directory.                          
194                                                                                     
195      http://www.cmake.org                                                           
196                                                                                     
197      First create a file called CMakeLists.txt with this content:                   
198                                                                                     
199      cmake_minimum_required(VERSION 2.8)                                            
200      project(test)                                                                  
201      file(GLOB files *.cpp)                                                         
202      add_executable(test ${files})                                                  
203      install(TARGETS test RUNTIME DESTINATION bin)                                  
204                                                                                     
205      then build and install your program test like this                             
206                                                                                     
207      erik@linux:~$ ls ~/codereview/                                                 
208      file.cpp  file.h  CMakeLists.txt  main.cpp                                     
209      erik@linux:~$ mkdir /tmp/build                                                 
210      erik@linux:~$ mkdir /tmp/install                                               
211      erik@linux:~$ cd /tmp/build/                                                   
212      erik@linux:/tmp/build$ cmake -DCMAKE_INSTALL_PREFIX=/tmp/install ~/codereview/ 
213      -- The C compiler identification is GNU                                        
214      -- The CXX compiler identification is GNU                                      
215      -- Check for working C compiler: /usr/bin/gcc                                  
216 up   -- Check for working C compiler: /usr/bin/gcc -- works                         
217 vote -- Detecting C compiler ABI info                                               
218 3    -- Detecting C compiler ABI info - done                                        
219 down -- Check for working CXX compiler: /usr/bin/c++                                
220 vote -- Check for working CXX compiler: /usr/bin/c++ -- works                       
221      -- Detecting CXX compiler ABI info                                             
222      -- Detecting CXX compiler ABI info - done                                      
223      -- Configuring done                                                            
224      -- Generating done                                                             
225      -- Build files have been written to: /tmp/build                                
226      erik@linux:/tmp/build$ make                                                    
227      Scanning dependencies of target test                                           
228      [ 50%] Building CXX object CMakeFiles/test.dir/main.cpp.o                      
229      [100%] Building CXX object CMakeFiles/test.dir/file.cpp.o                      
230      Linking CXX executable test                                                    
231      [100%] Built target test                                                       
232      erik@linux:/tmp/build$ ls -l /tmp/build/test                                   
233      -rwxrwxr-x 1 erik erik 7702 2012-04-12 16:58 /tmp/build/test                   
234      erik@linux:/tmp/build$ make install                                            
235      [100%] Built target test                                                       
236      Install the project...                                                         
237      -- Install configuration: ""                                                   
238      -- Installing: /tmp/install/bin/test                                           
239      erik@linux:/tmp/build$ ls -l /tmp/install/bin/test                             
240      -rwxr-xr-x 1 erik erik 7702 2012-04-12 16:58 /tmp/install/bin/test             
241                                                                                     
242                                answered Apr 12 '12 at 15:25                         
243      share|improve this answer                        [IMG]                         
244                                                Erik Sjölund                         
245                                                        1515                         
246           +1 for bringing up CMake, but please, please, never use file(GLOB). It    
247           completely breaks CMake (i.e. when you add or remove source files you     
248           will have to re-run CMake manually). Just list the sources explicitly.    
249           It's not so much work... – Michael Wild Apr 24 '12 at 9:41                
250           Interesting point. I looked around and found this stackoverflow question  
251      1    that discuss advantages and disadvantages of using file(GLOB). – Erik     
252           Sjölund May 2 '12 at 7:44                                                 
253                                                                                     
254      add a comment |  expand to show all comments on this post                      
256 Your Answer
258    __________________________________________________________________________
259    __________________________________________________________________________
260    __________________________________________________________________________
261    __________________________________________________________________________
262    __________________________________________________________________________
263    __________________________________________________________________________
264    __________________________________________________________________________
265    __________________________________________________________________________
266    __________________________________________________________________________
267    __________________________________________________________________________
268    __________________________________________________________________________
269    __________________________________________________________________________
270    __________________________________________________________________________
271    __________________________________________________________________________
272    __________________________________________________________________________
273     
274    draft saved
275    draft discarded
276    _____________________
278   Sign up or log in
280    Sign up using Google
282    Sign up using Facebook
284    Sign up using Email and Password
286   Post as a guest
288    Name _______________________________  
289    Email _______________________________ 
291   Post as a guest
293    Name _______________________________  
294    Email _______________________________ 
296    [ Post Your Answer ] discard
298    By posting your answer, you agree to the privacy policy and terms of
299    service.
301 Not the answer you're looking for? Browse other questions tagged c++ makefile or
302 ask your own question.
304    asked  6 years, 2 months ago 
305    viewed 9,894 times           
306    active 5 years, 3 months ago 
308     Related
310    7
311    Improving Makefile and general C++ project structure
312    3
313    Makefile — Platform Dependency
314    2
315    How can I improve this Makefile?
316    5
317    Generic Makefile
318    7
319    Makefile for C++ OpenGL with GLFW and glad
320    4
321    Simplifying a Makefile
322    4
323    Makefile for compiling shared libraries
324    3
325    Makefile for refactored recursive breadth first search Knight Tour
326    1
327    My first functional Makefile
328    6
329    Generic Makefile handling unit testing and folder structure
331     Hot Network Questions
333      * What is the use of that Internal rail?
334      * How close can planes fly to each other over the ocean?
335      * What does the pointer 'this+1' refer to in C++?
336      * Intuition regarding Limits.
337      * Within Fibonacci Numbers
338      * An English word (adj or verb) to describe your feeling when you did
339        not do something you were expected to do
340      * Will it halt? (Robbers)
341      * How to convert input expression to FullForm String
342      * How would deafening as punishment be carried out?
343      * How Long Could an Eternal Fire Last?
344      * What's the in-universe relevance for the name of Spider-Man:
345        Homecoming?
346      * Life Jacket for a person without arms?
347      * (bash) Script A, wait for script B, but not its child process
348      * Would pyrokinesis be an effective defense?
349      * What medical costs burden the military enough to warrant banning all
350        transgender people?
351      * Do the circles overlap?
352      * What RPG concepts does "rules as written" encompass?
353      * Project Euler Problem #8: Largest product in a series
354      * Will it halt? (Cops)
355      * Why isn't `|` treated literally in a glob pattern?
356      * Did JFK call himself a jelly donut in his famous Berlin speech?
357      * How to tell friends something goes against my religion?
358      * What kind of wire connectors are these?
359      * Is there a term for the part of a word that "pluralizes" it?
360    more hot questions
361    question feed
362      * about us
363      * tour
364      * help
365      * blog
366      * chat
367      * data
368      * legal
369      * privacy policy
370      * work here
371      * advertising info
372      * mobile
373      * contact us
374      * feedback
375 Technology                                                 Life / Arts       Culture / Recreation             Science          Other        
376                                                             1. Photography    1. English                                                    
377  1. Stack         1. Geographic                             2. Science           Language &                                                 
378     Overflow         Information        1. Network             Fiction &         Usage                                                      
379  2. Server Fault     Systems               Engineering         Fantasy        2. Skeptics                      1. MathOverflow              
380  3. Super User    2. Electrical         2. Cryptography     3. Graphic        3. Mi Yodeya                     2. Mathematics               
381  4. Web              Engineering        3. Code Review         Design            (Judaism)                     3. Cross                     
382     Applications  3. Android            4. Magento          4. Movies & TV    4. Travel                           Validated     1. Meta     
383  5. Ask Ubuntu       Enthusiasts        5. Software         5. Music:         5. Christianity                     (stats)          Stack    
384  6. Webmasters    4. Information           Recommendations     Practice &     6. English       1. Motor        4. Theoretical      Exchange 
385  7. Game             Security           6. Signal              Theory            Language         Vehicle         Computer      2. Stack
386     Development   5. Database              Processing       6. Worldbuilding     Learners         Maintenance     Science          Apps
387  8. TeX - LaTeX      Administrators     7. Emacs            7. Seasoned       7. Japanese         & Repair     5. Physics       3. Area 51
388  9. Software      6. Drupal Answers     8. Raspberry Pi        Advice            Language      2. more (32)    6. Chemistry     4. Stack
389     Engineering   7. SharePoint         9. Programming         (cooking)      8. Arqade                        7. Biology          Overflow
390 10. Unix & Linux  8. User Experience       Puzzles & Code   8. Home              (gaming)                      8. Computer         Talent
391 11. Ask           9. Mathematica           Golf                Improvement    9. Bicycles                         Science
392     Different    10. Salesforce        10. Ethereum         9. Personal      10. Role-playing                  9. Philosophy
393     (Apple)      11. ExpressionEngine® 11. Data Science        Finance &         Games                        10. more (10)
394 12. WordPress        Answers           12. Arduino             Money         11. Anime &      
395     Development  12. Blender           13. more (26)       10. Academia          Manga        
396                                                            11. Law           12. Puzzling     
397                                                            12. more (17)     
399    site design / logo © 2017 Stack Exchange Inc; user contributions licensed
400    under cc by-sa 3.0 with attribution required
401    rev 2017.7.27.26630
402    Code Review Stack Exchange works best with JavaScript enabled