180 points · by ingve · 2y ago · 157 comments
One, write unit tests in the same source as the implementation. Tests that run through the interface are good too and can be in separate source files, maybe in another directory. Fine grain poke at the internals of static functions really should be written as well and those are best placed where they can call said static functions directly. Make adding tests really low friction and write lots of them.
Two, embrace code generators. I've seen it written that C++ solves problems by extending the language and C solves problems by writing more C and that sounds about right. Make adding a code generator as low friction as adding a C source file. It should take seconds to convert an existing source file into a generator that recreates said existing source file.
People love ceremony. All the source files are written in lists in cmake files. All their build dependencies are written down in the cmake files as well. All the tests are written in list of tests to run. Every code generator is introduced as an independent project with it's own documentation and careful integration into the build systems.
I love writing C because I do none of that overhead. The files to compile are whatever is on disk. The tests to run are all the tests in the source, they aren't listed somewhere else as well. Any file called *.lua.c is a lua program that writes the intended contents of *.c to stdout. *.c.h will be compiled as C and then run to write a C header on stdout.
Convention over configuration with a language that requires zero cognitive overhead to write.
I couldn't agree more. I can't stand build tools that don't take globs! I shouldn't need to list the same thing in multiple places just to make it work. Almost all the time, the files on disk should be the only list needed.
You also don't need to limit yourself to the C pre-processor. There are other dedicated pre-processing languages, like M4, and templating languages you can use.
Python is good at generating C source. I changed to mostly using lua five years ago as python climbed the complexity curve. Sometimes the right thing is C itself, e.g. laying out data based on sizes of various C types. Currently I'm trying to use xslt to emit syntax trees that pretty print to get the generated source in what is probably a dead end.
I've always wanted to use Lua to generate boilerplate C code (like typesafe vectors) instead of relying on macros, so might actually start thinking in this direction going forward.
The advantage of a system like that over a plain programming language (such as Lua you mentioned) is that there's less escaping and string.format(xxx) sorts of things. The output text is the primary thing and the templating language has its own special syntax to "activate" it when you need it, rather than the other way around.
That being said, Lua's square-bracket strings are pretty good for bulk text, too (:
[1] http://template-toolkit.org/about.html
[2] https://jinja.palletsprojects.com/en/3.1.x/templates/#synops...
src/ contains lots of code in lots of languages, all describing code generators of varying complexity. src/foo.c uses 'cp' as the code generator. src/bar.c.py uses 'python'.
gen/ contains the result of the ad hoc code generators. Same tree layout as src, one to one map from those files. All of that is C. Files that get #included and don't make sense standalone I tend to suffix .data, e.g. src/table.data.lua runs to create gen/table.data.
obj/ contains all the C compiled to object code or llvm bitcode, depending on the toolchain.
I originally did that with the idea that I could distribute gen/ as the source code for people who wanted to build the project without dealing with the complexity of the build system, strongly inspired by sqlite's amalgamation. Sqlite is built from a chaotic collection of TCL and C code generators but you don't see that as a user of sqlite.c.
It turns out that debugging the stuff under gen/ when things go wrong is really easy. Valgrind / gdb show you the boring code that the generators stamped out. So in practice I keep that separation because it makes it easier to trace through the system when it behaves unexpectedly.
Lua does that really well. Good multiline string literal support. A template string that you call gsub() on a few times then dump to stdout is very quick to put together. You've got string format for more complicated things, maybe using one of the string interpolation implementations found on their wiki.
A unit test wouldn't know the calling context of procedures deep in the call graph, and cannot detect unsafe but seemingly working code.
I'm not sure why you'd say this. Testing has more to do with the developer than the language. The SQLite project is written in C and has 590 times more test code than source code [1].
Do you have any sample projects that showcase both the tests and the code generation? I'd love to take a look.
The projects using code generation in that fashion are proprietary. There's a makefile at https://github.com/JonChesterfield/boring-makefile/blob/mast... set up to do the src/gen/obj codegen by default structure.
Just made the ad hoc xml codegen hackery public, some examples of tests written a couple of days ago at https://github.com/JonChesterfield/xml/blob/main/tools/intse...
Go slightly further and write out function types like that and you get something equivalent to swig, where instead of parsing C and trying to emit wrappers for other languages from that framework, you have the data in native lua tables that you emit code from.
The project structure includes flavour-of-the-week litter like .devcontainer, .github, .vscode.
compile_commands.json should be getting generated, not stored.
Not sure if I would recommend anyone follow this information.
The build system situation in the C world is dire. And I should know, given I write my own build systems for C.
I would say, while I've never actually used it, Meson seems the least non-sensical out of the box experience.
Ideal in some ways but not in others is designing and implementing your own build system because genuinely everything else out there has some major shortcoming or other.
If you are insistent on make, stick to GNU make, read the GNU make manual, understand make and then write something simple and non-recursive.
This is the most recent Makefile I helped create:
CXX ?= clang++
CXXFLAGS += -std=c++20 -Wall -Wextra -fsanitize=address -ggdb3 -MMD -MP
LDFLAGS += -fsanitize=address
OBJ := program.o parse.o
all: program compile_flags.txt
program: $(OBJ)
$(CXX) $(LDFLAGS) $(TARGET_ARCH) $^ $(LDLIBS) -o $@
$(OBJ): Makefile
compile_flags.txt: Makefile
printf "%s\n" $(CXXFLAGS) >$@
clean:
$(RM) *.o *.d program compile_flags.txt
-include $(OBJ:.o=.d)
.PHONY: clean
If you want to do something like run a linter, code formatter, etc, before building, then this should be performed by a script which calls into make. Make is not designed to be used as a switch statement for your bash snippets.Didn't actually know that was a thing until I accidentally ran into it yesterday when I ran the make command in the wrong terminal window and the build was very, very unhappy.
At least it didn't bork my entire /home directory like that time we don't talk about...
My general rule is Make for simple things and CMake if it involves distro-packed library deps or I'm building python modules with complicated enough builds that I don't wan't to beat the dead horse of distutils into submission.
Honestly, if I can't tell what the build system is doing without having to ask google then it's way too complicated.
CC = clang
CFLAGS = -g -std=c2x -Weverything -fsanitize=undefined,address
all: app.exe
app.exe: src/main.c
$(CC) $(CFLAGS) src/main.c
clean:
rm -rf /build
See my comment here with an example of an NMAKE Makefile.
Consider:Meta's Buck 2 (written is Rust) would be my choice, if I would write "new" C or C++.
Examples using Vcpkg
https://github.com/Release-Candidate/Cxx-Buck2-vcpkg-Example...
And Conan
https://github.com/Release-Candidate/Cxx-Buck2-Conan-Example...
This is why you still see a lot of important C project support autotools even though it's a pretty awful developer experience.
While I recommend anyone who uses GNU make should read the manual, the manual is full of outdated best practices which can be safely ignored.
If I was going to use this makefile for my own project, I would even drop the clean target entirely. phony targets are mostly a misfeature. Although it looks like the makefile as accepted by the project hasn't marked the all target as phony.
But go on, tell me what it is that is not recommended specifically. I am aware of many deviations from what the GNU make manual claims is recommended. A large portion of deviations is the lack of many of the standard targets it thinks should be provided. Another deviation might be the uppercase OBJS should be lowercase according to the manual, but in this case I was trying to minimize the number of immaterial changes from the original makefile I modified to arrive at this point since it was not my project.
>If you are insistent on make, stick to GNU make, read the GNU make manual, understand make
I refer to this authoritative sounding comment while you miss out on the very basics like that.
This is the approach I take with my C and C++ projects, although I've swapped meson out for CMake. I still have my CMake projects generate pkg-config files as well so that I don't force CMake on any consuming projects (just because I suffered with CMake doesn't mean you have to, although you can as well :))
Does it? IIRC something like
build/%.o: src/%.c include/*.h
$(CC) -c $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
works well enough for small projects. TEST_SRC = $(wildcard *_test.c)
If you follow TFA's guidelines about having a `src` dir, then: SRC = $(wildcard src/*.c)
And if you need to convert that to a list of matching .o files, `patsubst` is your friend: OBJ = $(patsubst %.c,%.o,$(SRC))
So now simply dropping a file into the right place (or a unit test ending in _test.c) won't require any makefile changes.I tend to copy my most recent Makefile into my next project and generally it stays 90% the same (I have to edit a few macro definitions and rules, but not many).
Personally, I tend to prefer specifying the files individually - it doesn't take up that much developer time nor much space in your Makefile, and makes it considerably easier to debug building issues when using a sandboxed environment (such as Nix or Bazel).
[1]: https://www.gnu.org/software/make/manual/html_node/Catalogue...
example: build/blah.o
echo nothing special
.PHONY: example
...requires blah.c to be in build/.My entire build system in Rust projects consists of the commands "cargo build", "cargo run", and "cargo test" and I have yet to find a reason to deviate from the default filesystem structure or configurations.
To be clear there are real reasons to still be writing C. No hate to the author of this post. I just don't want to be doing it any more in most cases.
No other language community does this to other language discussion. Even C++ fanatics didn't do this back when C++ was being sold as a C replacement.
This is an entirely new and somewhat sad, phenomenon: the need for the rust community to derail any and all discussion about some other language reeks of a community that feels threatened.
so yes, you pointed out the moniker of the individual doing this. It doesn't obviate the point.
This makes no sense. Almost by definition, anyone derailing a discussion to mention $FOO is a member of the $FOO community.
It's disingenuous to suggest that all derailment is due to non-$FOO advocates.
> There is nothing new or sad about it.
The phenomenon of persistent derailment is, in fact, something that I had not seen until Rust arrived.
It is new, it's limited only to Rust advocates as a group, and I find it sad.
2. For comparison, I've almost certainly crossed the million lines of C mark years ago--if anything, I'm the C community.
3. You and I remember very different things about the C++ community. In fact, I also remember a number of other languages being offered as alternatives to C over the years including some obvious ones like Pascal or Basic, and also including some real absurdities like Lua (nothing wrong with Lua, but it's really not for the same kinds of projects as C). The idea that comparing your language to C is some sort of new phenomenon, is flat wrong.
4. You're ascribing a lot of intent to me bringing up Rust which isn't there. I'm not trying to derail the discussion--if you want to talk about C, do it.
5. The idea that the Rust community is threatened by C is a bit bizarre.
- Rust? Why not Nim?
- Nim? Why not Zig?
To start a new project today using plain GNU Make like the author of the article recommends, is not a good idea unless you enjoy fiddling with the build.
Not comparable at all.
The difference is Cargo is the official standard package manager of the Rust language. Meson is one among the sea of incompatible build systems for the C language.
As with the lesson gofmt taught, you must supply the basic feature in the box. Humans are lazy, so if it doesn't come in the box only people who know they can't live without it will even bother, put it in the box and only people who can't live with it will remove it.
That's not a distinction I care about. The tooling around a language should be a part of discussing the merits of a language. Your language can be the most ergonomic language in the world, but if all your development gains are lost fiddling with build tools, you haven't gained anything.
> Have you tried using a more modern tool like Meson?
I haven't, but now that I know about it, I'll give it a try. Thanks for the info! It looks promising.
> To start a new project today using plain GNU Make like the author of the article recommends, is not a good idea unless you enjoy fiddling with the build.
Maybe, but that just brings up the problem that there isn't really a clear second-tier system outside the standard library for tools. Certain tools (i.e. Valgrind) are well-known, but there are a million different ways to install a million different tools and for most things it's ultimately more common to just roll your own.
But being able to print "make: ** No targets specified and no makefile found. Stop." to stderr isn't particularly useful, and having to write a Makefile is a significant barrier.
Here is a C build system:
cat all.c
#include "foo.c"
#include "bar.c"
#include "main.c"
clang all.cso you can add run-time defines.
But I don't want to solve trivial problems. That's not where the value is.
But, there is plenty of excellent documentation available for using build and packaging tools of your choice to work similarly to Cargo.
To be honest, the moment I have to evaluate a dozen tools, pick one, and use it, even if that tool does manage to be "$TOOL build" and literally nothing else which I don't think is anywhere near something people can count on in the C world, it has already proved to be harder than "cargo build".
C has been around for over 50 years. It predates many of the modern "everything including the kitchen sink" style of language platforms. It has spread across so many platforms and uses that a Cargo like integration is not going to happen.
But, this does not mean that build, package, and install tools don't exist. If you want me to provide you with a single tool to rule them all, well, that's impossible for the reasons I listed above. But, depending on which platforms you care about and which features you want, there are plenty of existing tools.
If your goalpost is "change C to be like Rust and have a single build tool", then that's impossible. If your goalpost is "find me a tool that does X, Y, and Z", then there that is certainly possible. There are Cargo clones for C/C++ that work just fine.
Make is annoying but Makefile issues are found quickly and easily when running `find . | entr -c make` and saving the source file often.
C will build and run in places rust can't.
so I should argue C is better because in my chosen metric (diversity of platforms) it wins.
Sure, and there's plenty of documentation for Cargo too. Or at least I assume there is, but I've never had reason to read it.
Do you see the problem with what you're saying?
No, I don't. At some point, you read documentation, or a tutorial, or example code to use Cargo.
These exist for other build and package systems, some of which are clones of Cargo.
If you want a white glove experience (e.g. cargo new), such systems exist as well for C. Cargo is nothing new.
What about "gcc mycode.c" or "make"? You shouldn't need to reinvent your build system every project.
For projects of any significant size, you're going to run into some constraint which requires you to use `make` differently than you have before.
That's precisley why official/standard build systems suck, they are extremly cumbersome to wrangle when you go off the beaten path.
So the irony is that standard build systems/package manager are whats good for hello worlds, non-trivial programs require custom build steps.
Just let me write a build.bat/build.sh per platform/compiler/configuration that are explicit and precise in compiler flags, paths, output files, pre/post processing, etc so nothing magical is happening under the hood.
e.g., where do I put crate::, vs module X, vs module X{ } again? Do I have to specify it in the automatic lib.rs too? Or ...
C at least lives on the filesystem and you tell it where to grab things.
Sure, but there's one clear answer to that question which you can refresh your memory of in under 3 minutes of reading.
C does live in the filesystem, but where in the filesystem? Oh and it doesn't always live in the filesystem--sometimes it lives in the package system.
Then each platform gets its own directory with .c files.
ie... platform.h
platform_windows.c platform_linux.c etc.
This way, my build file for windows uses platform_windows.c, etcetc.
For libraries, it is critical that a distinction be made between "header files that will be installed" (which should use the project name as a directory prefix!) and "header files used internally". I put the latter in src/ but practice varies widely.
I argue that the flat layout is somewhat harmful (though at least using src/ beats shoving everything in ./), because even small projects eventually grow a distinction between "source files that are part of the main installed project" and "source files used solely for maintenance tooling".
Making a distinction between "code that needs to be cross-compiled" and "code that needs to be native" is useful even if you're not planning to do cross-compilation.
Similar to the cross compiled / native distinction, it's probably a good idea to put platform specific things behind an interface up front. Link time is a good point to swap out win32 for linux or similar and implementing the second target is much easier if you drew the line up front. The platform layer might also be one worth writing a mock for as part of testing.
Using manual header guards is a bug-prone waste. Nobody has ever demonstrated me a case where `#pragma once` fails to work with compilers from the last decade or two.
I've found it more helpful to have a PREFIX=$(pwd)/build or even PREFIX=$HOME/.local as an installation destination. And have a .env add PATH=$PREFIX/bin:PATH
Zig really removes a lot of hurdles in the onboarding process and let you jump into building software right the way.
Just have a look at how many C make replacement exists
Also, being able to cross-compile would be cool. But I guess cosmopolitan solves this.
Package manager: dynamic libraries! Or if you want to get really advanced, pkg-config and related. (or static libraries even. Common enough in embedded space!)
Dynamic analyzer : valgrind, gdb, Visual Studio, xCode, ...
Cross compiling : more platforms supported by C compilers than by any other build tool. Oh sure, you need to eventually watch byte sizes (as 8 bit bytes are a fairly narrow set of platforms), and know something about the platform's kernel API (if any, lots of embedded platforms are just hardware interactions!).
So I'll assume this is satire.
All I've seen in practice is "vendoring", which amounts to copy the source into your tree with some degree of review or patching, and then go on as before. After being initially indignant that we didn't use libboost from the OS that approach has really grown on me.
Dependency management is a horrendous mess. Moving the logic into package managers hides that mess from the day to day development which is very nice. However, following a debugger into the binaries that came from apt install is not a great time. Patching the source to behave differently while trying to work out what is going wrong is rather harder too.
If you do the vendored thing, you also get the interesting feature where you can checkout the source tree as it was eight months ago to correspond with whatever a customer is asking about and it builds and runs, instead of telling you that the dependencies no longer exist.
I'm now heading further in that direction. All the libraries should be built from source in the same repo, but preferably by tools that are also in that repo. I'm going to end up with a C compiler checked in as well, much like the embedded toolchain people are prone to doing.
We had a build fail for a few days because a git commit with a given hash didn't exist upstream. Solution? Pin to a branch of course! Vendoring as that solution takes a surprisingly deep realignment.
[0] https://andrewkelley.me/post/zig-cc-powerful-drop-in-replace...
Conan, gdb/DDD, Rational Purify etc. exist and can be replaced/improved by better tools.
1. instead of folders for sub-systems at the top level, put them all into src/.
2. I use the name ext/ instead of lib/ for external libraries, because in POSIX, the lib/ name indicates where the binaries of static and dynamic/shared libraries reside (not their sources).
I use a simple sh script called mkprj <project-name> to create that folder hierarchy for a new project.
In all these years I've yet to see another person (other than me) to use ramdrive for temporary files. Is everyone okay with slow compilation and SSD rape or am I missing something?
Just remove best-practices, it's a silly phrase.
I've found it more helpful to have a PREFIX=$(pwd)/build or even PREFIX=$HOME/.local as an installation destination. And have a .env add PATH=$PREFIX/bin:PATH
[0] https://xmake.io
https://jera.com/techinfo/jtns/jtn002
Consider using Clang-Tidy with
`-*,cert-*`
(Which disables all default options, and checks your code according to the Secure coding standard (CERT) ruleset.)Use Clang-Format as well. If you use Clang, consider `-Weverything -fsanitize=address,undefined` and disable options that you do not need. Consider using NMake or Make (or just write a simple script to automate building the stuff).
Here's a Google-esque style guide for C:
https://gist.github.com/davidzchen/9187878
At least, this is my approach.
CC = cl.exe
LD = link.exe
CFLAGS = /Od /Zi /FAsu /std:c17 /permissive- /W4 /WX
LDFLAGS = /DEBUG /MACHINE:X64 /ENTRY:wWinMainCRTStartup /SUBSYSTEM:WINDOWS
LDLIBS = user32.lib gdi32.lib
PREFIX = ../src/
all: app.exe
app.exe: app.obj
$(LD) $(LDFLAGS) /OUT:app.exe app.obj $(LDLIBS)
app.obj: $(PREFIX)app.c
$(CC) /c $(CFLAGS) $(PREFIX)app.c
clean:
rmdir /q /s build