8 ms·
A Simple Makefile for Medium-Sized C/C++ Projects
- kmm 10y agoNeat! I've been putting off learning how to use those `-M` flags to automatically generate dependencies, but it looks like it's not that hard :) What I also like to do is hide the actual compilation command with recipes like this, inspired by the Linux kernel %.o : %.c @echo " CC $<" @$(CC) -o $@ -c $(CFLAGS) $< I think it looks a lot tidier, it turns a ton of dense uninteresting command lines into a few dozen short lines.
- qznc 10y agoA variant we use is: Q ?= @ %.o : %.c @echo 'CC $@' $(Q)$(CC) -o $@ -c $(CFLAGS) $< Now you can make the commands visible again via `make Q=`. A more subjective question is, if you echo $@ or $<.
- andrewaylett 10y agoIn a past life, the mega-but-autogenerated Makefile I helped maintain would store the executed command and only echo it if the command failed. And we logged everything to file, so you got nice output but all the info was there if we needed it. Didn't take that long to work out how to do it, once we'd decided it would be a nice thing to have.
- qznc 10y agoI like that. It lives the Unix philosophy to be silent unless an error occurs.
- m_mueller 10y agoI did the hiding for a while until I noticed that it slows my debugging down way too much when something breaks and I want to manually fiddle with some compiler flags. Now I let make use two separate colors: One for info I'm usually interested in and one for stuff I need to know when I need to get my hands dirty.
- Davidbrcz 10y agoJust use cmake or scons. In 2016, you should not hand write a single makefile ! A simple cmake/sconcs build file will be as simple as the one shown (or even simpler !) and it will definitively will be easier to integrate external dependencies if you have to.
- elcct 10y agoWould be nice if you could give an example, not just "use that".
- onli 10y agoEspecially since scons and cmake are in no way easy to learn, imho.
- realharo 10y agoStill hell of a lot simpler than hand-writing Makefiles though. For both small and large projects. I mean, a "hello world" CMakeLists.txt can be literally just this: add_executable(hello hello.c) And it's cross-platform, can generate Visual Studio/Xcode/... projects, etc.
- onli 10y agoI think we have to go deeper than that to really see an advantage of cmake. A corresponding makefile would be: all: hello That's not really complicated either.
- radarsat1 10y agoExactly. When evaluating a language / build system / whatever, it is definitely not sufficient to look at Hello World. You have to evaluate the worst case and average case if you want to get an idea of what you're in for. Looking at the "best case" (simple one-file project) tells you almost nothing except how hard it is to get started.
- greydius 10y agoWe must be using a different definition of simple. I've never seen a simple makefile.
- wyldfire 10y agoWell, with implicit rules IMO you can get really simple but productive makefiles. e.g. (not "medium-sized" project, but illustrates the simplicity) https://gist.github.com/androm3da/9b5575fb288045775c178a4fb2483438 https://gist.github.com/androm3da/9b5575fb288045775c178a4fb2... here's a slightly more feature-rich example, still relatively simple IMO. https://gist.github.com/androm3da/9126ff51b5b47f69b99b1e3db845d85b https://gist.github.com/androm3da/9126ff51b5b47f69b99b1e3db8...
- onli 10y agoI do like simple makefiles. I adopted a C++-project without having much C++-knowledge, and simplifying the build setup was a big step in making it mine. Thinking that it might be nice, I tried this one instead of my own approach at a simple makefile (https://github.com/onli/simdock/blob/master/Makefile https://github.com/onli/simdock/blob/master/Makefile) and I get this error: > Makefile:16: * missing separator. Stop. Which raises kind of an important point: Simple means understanding what is happening. I have no idea why `$(CC) $(OBJS) -o $@ $(LDFLAGS)` does raise that error - and just like that it is not simple for me anymore. Edit: Now with the tab-error out of the way, it of course does not find the dependencies. That might be caused by a strange project organization (like said, it is an adopted project) or maybe the makefile is just not complete – I'm not sure how far the auto-generation is supposed to go. Played a bit with it, but that just removes the simplicity. For now, I think that the pkg-config way is nice and explicit, and would recommend to take a look at the linked makefile if a simple one is searched. Though I still would be happy about optimizations for that file! I of course just might miss the point. Well, after all that supports mine: Not that simple after all.
- stevekemp 10y agoSadly you're bitten by the biggest misfeature in Make - You must use TABs not spaces.
- revelation 10y agoYour editor probably automatically converted tabs into spaces. And just like that, the Makefile stops working. Which proves the point: Makefiles are at a point in life where they should be exclusively automatically generated. The only exception are throwaway projects where you and only you use it.
- mbrock 10y agoI strongly disagree. The tab requirement for Make is very well known and less strange than custom Makefile generation. Simple Makefiles work extremely well in lots of projects.
- rwmj 10y agoPlease don't brew your own build system. It likely won't handle at least one of the following situations: * installing into a DESTDIR * setting custom CFLAGS/LDFLAGS * changing prefix, libdir, sysconfdir * cross-compilation * parallel builds * conditional features * missing requirements and will make packaging your software in Linux distros much harder than it needs to be.
- deleted 10y ago[deleted]
- pja 10y agoThere’s no point telling people not to do something if you don’t give them an alternative that does do all those things. (And no, “just use autotools” is not a viable answer.)
- rwmj 10y agoAutotools does do all of those things. I'm not a particular fan of it either, but when I'm packaging software for a Linux distro then I'd rather see autotools or cmake being used instead of some crappy custom build system that will require patching to make it work. There is room for someone to come up with a good build system. It had better do everything autotools and cmake do, and be well documented and widely used, so there's a rather large barrier to entry.
- _RPM 10y agoAuto tools is great. To compile all you do is ./configure make make install It couldn't be simpler. Even though I am part of the GitHub generation, I don't see why so many of my peers hate it. I actually like it.
- wyldfire 10y agoThis is kinda hilarious because, yes, "Autotools is great" [as a consumer]. But autotools and m4 is kinda awful to write IMO.
- ape4 10y agoJam is nice and simple https://www.perforce.com/resources/documentation/jam https://www.perforce.com/resources/documentation/jam
- Merad 10y agoIt always annoys me that we don't have better solutions for building C and C++ projects by now. My own take on the generic drop-in makefile[1] has over 1000 stars on github, which says pretty loudly to me that this is a common pain point for many people. Alas I haven't had a brilliant idea for a solution (yet). [1]: https://github.com/mbcrawfo/GenericMakefile https://github.com/mbcrawfo/GenericMakefile
- vvanders 10y agoThe solution is good tooling, Visual Studio makes this a non-issue with sane defaults that can be extended if needed. I haven't tried CLion yet but I would assume it's decent given JetBrain's track record.
- realharo 10y agoTrue. Other languages have it way easier because: - proper module system, none of this header file nonsense - no compiler flags to worry about - no preprocessor definitions to worry about - as a consequence of the above, no dependencies that require their own linker flags, include directories and preprocessor definitions to work - no need to support different compilers/platforms with different configurations (which work differently with libraries that require different linker flags and include directories and...)
- 72deluxe 10y agoOut of curiosity, how do other languages cope with: a. Targeting different release types (debug vs release) b. Changing behaviour of the compiler c. Having different code paths between debug and release (#ifdef _DEBUG) d. Having macros and helpful macro expansion I do not understand the dislike of header files: how would you recommend distributing DLLs and libs while exposing their functions to be developed against? I suppose you could implement everything in a header file if you wanted a simple "module" system (thinking of the header as a module), but this would establish a very simple system with no interdependencies or reusability.
- jayd16 10y ago
- bobbyi_settv 10y agoThis approach is flawed because it uses "find" to discover the source files which means that if you delete a source file, it won't cause a rebuild since it won't see any changed files.
- asveikau 10y agoAlso you can't conditionally build a .c or .cpp file without ifdefs in the source. Also you have to wait for find to run before any building starts. Can be slow for a large project.
- stormbrew 10y agoIt's probably possible to adapt it to do that by using find much like you use gcc -MM to get header deps, generating a make snippet that you then depend the executable output on. But then we're getting pretty nasty.
- deleted 10y ago[deleted]
- TickleSteve 10y ago"But because Make works backward from the object files to the source, we need to compute all the object files we want from our source files". No.... don't do this. Make is intended to work the other way around... it finds the source from your targets. Define your VPATH and let it find them. This is what loads of people do and is why there are so many Makefiles are packed full of macro-magic!
- wyldfire 10y agoTotally agree, they should use VPATH. And that way they could've just skipped to the implicit rules version.
- Tyr42 10y agoI do agree that VPATH is helpful, but you'd still need to put the Makefile into the build directory in that case, which is distasteful, as it's not a built file. Also you can't really get around specifying the files or searching, unless you have one c file per executable.
- jimparis 10y agoProjects that make blind use of VPATH are a pain. You can't have the same filename in two different directories! It's a hack at best, and using explicit paths (as this Makefile does) is a lot more reliable.
- danidiaz 10y agoTranslating that Makefile to Shake http://shakebuild.com/ http://shakebuild.com/ would be a good Shake learning project...
- vanilla 10y agoThis is not simple. I haven't made my own Makefiles, because when I see them, they are complex and not easy to understand. That's why I chose CMake for my projects. If this is simple, I chose the right build tool. This build file of a large project is easier to understand than the "Simple Makefile" https://gitlab.kitware.com/vtk/vtk/blob/master/CMakeLists.txt https://gitlab.kitware.com/vtk/vtk/blob/master/CMakeLists.tx...
- raarts 10y ago> they are complex and not easy to understand. Makefiles are declarative, which is a bit strange at first. If you start with a simple one you pick it up really fast.
- flohofwoe 10y agoThe problem with Makefiles is that they don't work on Windows with Visual Studio, and generally only have very limited support in IDEs like Xcode, QtCreator, etc... and once stuff like cross-compilation and feature selection comes in, they get really messy really fast. That's where meta-build-systems like cmake etc come in. They all have their faults (cmake has a terrible scripting language), but they solve real problems for non-trivial projects.
- makecheck 10y agoI agree that cross-platform is tricky and in the past I have used SCons with some success for that. Although, at least for Xcode, I can build my entire Xcode project from a Makefile: you just have to use command-line tools like "xcodebuild", and if you want a clickable version you set up a build phase that runs "make". And, while Apple’s ".xcconfig" files are not exactly "make" syntax, they support a subset that looks exactly the same so it is possible to have files with variable settings, etc. that can be referenced by both Xcode and any Makefile that needs to stay in sync. Environment variables are yet another option.
- GreaterFool 10y agoI'm going to take this opportunity to rant about sad state of C++ open source. I would really really like to write some C++ but I'm not a C++ guru; so I tried installing facebook/folly and facebook/fatal on my Mac OS. That just doesn't work. It wasn't written cross platform and it probably never will. So I spun up a ubuntu VM and tried there. fatal compiles, folly still doesn't... And so ends my brief foray into C++. At that point I started researching how can I bind the library I need to Rust so I can skip all this nonsense. C++ is not a bad language and I would like to write a project hat uses it. But I'm just a user of the language. I don't have time and expertise to tackle those build issues and quite frankly installing any library is a major PITA.
- simfoo 10y agoHave a look at Conan [https://www.conan.io/ https://www.conan.io/] then. It has solved the problem you described and its usability is great
- 72deluxe 10y agoWhy not just use Xcode and xcodebuild from the CLI if you don't like the IDE? I write all my OSX projects in C++ using it. Learning to build projects and solve compiler and linker errors is part of the journey. Stroustrup's book takes longer to read than 5 minutes, so writing C++ will take longer. It is a rewarding journey, where you will suddenly find all other languages (Java, C#, C, JavaScript, Swift) very similar or simplified in comparison. To get you started you could install xcode and the commandline tools, write your file.cpp and use: g++ -o myprogram file.cpp This assumes no linker options, no preprocessor options or anything, and on OSX will use clang, which it secretly symbolic links as g++. You might find it easier to get your head around it by starting a project in Xcode, setting the options in the IDE and then observing the output that it runs. Note that installing a library on most Unix platforms isn't complicated - configure, make, make install.
- wyldfire 10y agoC++, regardless of open/closed source is not in a sad state IMO. The problems you describe sound like they're from the perspective of someone who's worked with much higher level languages. C++ is as good (or as bad) as it's always been, it hasn't evolved to a bad state. New language designers have the luxury of having been bit by C/C++'s misfeatures and wrinkles. They also have the luxury of high end computers which can solve lots of problems in reasonable computation time. This means that modern languages can afford to trade off more computation resources in favor of development simplicity. > But I'm just a user of the language. I don't have time and expertise to tackle those build issues and quite frankly installing any library is a major PITA. I have a hard time understanding what "just a user" of the language means. It sounds like you're confessing to being a novice. That's fine, but you should be prepared to have to do a lot of work before you become proficient in C/C++. Much more so than modern languages.
- imron 10y agoI'm a big fan of meson [0]. The one thing it doesn't have over this Makefile is automatic detection of source files - you need to manually specify them. I haven't found that to be prohibitive in practice. 0: http://mesonbuild.com/ http://mesonbuild.com/
- gkya 10y agoBSD make (bmake) and its .mk includes are really simple, it's basically make with batteries included. Many makefiles may be reduced to two lines while no new syntax is introduced: PROG=${.CURDIR:T} .include <prog.mk> It indirectly extends original BSD make. There are some syntactic differences from GNU make, but no big depart. See http://www.crufty.net/help/sjg/bmake.htm http://www.crufty.net/help/sjg/bmake.htm Here is a custom BSDmakefile for my website, a more extensive example where the mk libraries can't apply: # makefile -- Build the website. # # $Id: makefile,v 1.10 2016/08/15 12:55:49 igk Exp $ # # M4=m4 AWK=awk SED=sed TIDY=tidy5 TARGS=-i -utf8 include config.mk # Common templates for each output file. MACROES=html.m4 config.m4 TMPL=${MACROES} meta.m4 header.html.m4 HERE footer.html.m4 HTML+=${LISTS:S/$/.html/} ATOM=${LISTS:S/$/.atom.xml/} OUT=${HTML} ${HTML:S/html$/&.m4/} ${HTML:S/html$/&.dirty/} ${ATOM} .MAIN: ${HTML} ${ATOM} # Generate lists. .for L in ${LISTS} $L.txt: $L.list ${AWK} -f list.awk ${.ALLSRC} > ${.TARGET} $L.atom.xml: $L.list ${AWK} -f atom.awk ${.ALLSRC} \ | ${M4} ${MACROES} - \ | ${SED} '1,2d' > ${.TARGET} .endfor .ifndef NOTIDY .for P in ${HTML} $P : ${P}.dirty ${TIDY} ${TARGS} ${.ALLSRC} 2>/dev/null > ${.TARGET} || true .endfor .for P in ${HTML} $P.dirty : ${TMPL:S/HERE/$P.m4/} $(M4) ${.ALLSRC} > ${.TARGET} .endfor .else .for P in ${HTML} $P : ${TMPL:S/HERE/$P.m4/} $(M4) ${.ALLSRC} > ${.TARGET} .endfor .endif # NOTIDY .for P in ${HTML} ${P}.m4 : ${P:S/html$/txt/} $(AWK) -f page.awk ${.ALLSRC} > ${.TARGET} .endfor clean: rm -f ${OUT} .PHONY: uuid pub ssh anal uuid: sh ./make-uuid.sh pub: sh ./publish.sh ssh: sh ./s.sh anal: sh ./analytics.sh
- westymatt 10y agoDude use cmake like a proper adult
- westymatt 10y agoUmmmm use cmake like a proper adult
- sctb 10y agoPlease comment civilly and substantively or not at all. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- oso2k 10y agoThis is a good start. Could be made a bit more minimal. I'll throw my base Makefile into the fray [0]. It supports cross compilation, CFLAGS & LDFLAGS usage, dependency file generation, source file autodetection (add the file to right folder and it's automatically included in the build), library building (`make lib`), Continuous Integration (`make start_ci/stop_ci`), Continuous Testing (`make start_ct/stop_ct`), Continuous Deployment (`make start_cd/stop_cd`), Installation (`make install`), Uninstallation (`make uninstall`), parallel compilation (`make -j4`), there's some build machine detecting/autoconfiguration support, build artifact generation, and even some git shortcuts (`make gstat/make make gpush`). All in about 190 lines of Makefile (including some comments, and lots of blank space lines). It does depend on GNU watch if you use any of the `start_/stop_` targets. I'm about to add self-documentation to it as well. For more minimal, comprehensible approaches, see the work of the suckless people [1][2][3]. [0] https://github.com/lpsantil/NewProj https://github.com/lpsantil/NewProj [1] http://git.suckless.org/dwm/tree/Makefile http://git.suckless.org/dwm/tree/Makefile [2] http://git.suckless.org/sbase/tree/Makefile http://git.suckless.org/sbase/tree/Makefile [3] http://git.suckless.org/ii/tree/Makefile http://git.suckless.org/ii/tree/Makefile
- posterboy 10y ago> a bit more minimal ie. smaller, which is ironically smaller than the quote edit: compared to 'gcc $CFLAGS $LDFLAGs <...> *.c' it's all rather bloated
- banachtarski 10y agoCan we kill raw makefiles already? Projects that don't handle out of source builds in a sane way are awful to integrate.
- zbuf 10y agoNice to see people spreading good practices with Make. Too many folks don't understand good use of Make and thus are doomed to re-invent it badly. I've had to use too many build systems that are, basically, big and flat lists of variables you can set. And yes I'm pointing at everything from esoteric in house systems to mainstream ones. Make's system of overrides is something especially useful.
- raarts 10y agoThis. Make is highly underrated. It's old so it's probably clunky, has a weird syntax and dog slow. Well no. So many examples of people reinventing the wheel, it's just sad.
- lttlrck 10y agoI feel like the only person in the world that uses Boost Bjam (for a proprietary project). I feel like I should switch but every time I look into it and read comments it's not at all clear that Bjam was a bad decision - even if it feels like I was the only one to choose it :-) It's simple, seems pretty fast but it is very hard to integrate custom build steps.