23 ms·
Ask HN: Good C++ code bases to read?
Hi All, I managed to avoid having to write C++ for all of my career. However, especially with SDR, I find my need to write C++ and my brain is so grooved reading C code that I find it trips me up reading C++ code. Also I find I don't have a good sense of "clean" C++ code. Since I learn best by exploring, I was wondering if there are some good code bases to read where I could get a feel for what "good" C++ code would look like.
Any suggestions? Pointers to repos would be appreciated. Thanks!
- deleted 6y ago[deleted]
- speedgoose 6y agoThe fact that your post got upvotes and therefore views but no one suggested an example of good c++ code speaks for itself.
- _a1_ 6y agoIt's probably because there are lots of non-C++ programmers who are curious about C++.
- skocznymroczny 6y agoBecause it's hard to define good C++ code. Many people would consider STL and Boost code to be good C++ code, but good luck trying to read through it.
- znpy 6y agomeh, given pretty much any X, different people will have different opinion about what is a "good X".
- ddevault 6y agoThere is no such thing as good C++ code.
- gpderetta 6y agoPlenty of examples at this time. It seems that your comment follows the usual HN comment pattern. That also speaks for itself.
- speedgoose 6y agoTrue.
- gtirloni 6y agohttps://github.com/scylladb/seastar https://github.com/scylladb/seastar https://github.com/scylladb/scylla https://github.com/scylladb/scylla https://github.com/catchorg/Catch2 https://github.com/catchorg/Catch2 https://github.com/facebook/folly https://github.com/facebook/folly
- cltby 6y agoStrongly seconded. Beyond the language aspects, the scylladb projects are full of instructive architectural ideas and design choices.
- PeterCorless 6y agoA good blog I wrote up based on Avi Kivity's talk at Core C++ 2019. Also our blog on using io_uring and eBPF: • https://www.scylladb.com/2020/03/26/avi-kivity-at-core-c-2019/ https://www.scylladb.com/2020/03/26/avi-kivity-at-core-c-201... • https://www.scylladb.com/2020/05/05/how-io_uring-and-ebpf-will-revolutionize-programming-in-linux/ https://www.scylladb.com/2020/05/05/how-io_uring-and-ebpf-wi...
- whimsicalism 6y agoHaven't looked through the scylla codebases, but can definitely recommend the latter two.
- juangburgos 6y agoIt is athough question, given that C++ is multi paradigm and recently changing a lot (last 10 years). There is: * Classic C++ (before C++11) * Modern C++ (after C++11) * Object oriented C++ * Functional C++ * Metaprogramming (Template) C++ * I am sure there are more examples... There is also whether you plan to use a specific library or not. For example I have used Qt for a long time and never touched the STD (standard library) or STL (standard template library). Qt has its own Qt way of doing things. You might need to be more specific as to which is the dommain that you want to apply C++.
- jll29 6y agoIn my view, (1) the "flavors" of the core language (listed by you); (2) the libraries/"frameworks" used (Qt vs. STL vs. Boost vs. ...) (also listed by you); and (3) the paradigm/style (OO vs functional vs generic meta-programming) generate a 3-dimensional space of ways of coding that are compatible with one another. It's almost impossible to use multiple libraries together without wrapping everything in one's own "house" style as a consequence. In contrast, languages like Java and Rust, for example, have one single standard way of doing things that 99% of people just follow.
- mattivc 6y agoOne of the C++ project that have influence my programming the most recently, which is to move to a style that is something between C and C++, is Dear ImGUI: https://github.com/ocornut/imgui https://github.com/ocornut/imgui
- iorrus 6y agoDo they have a coding style or similar in which this is outlined? I had a quick look at the code but I would be interested in what "a style that is something between C and C++" actually entails. Avoiding templates but using classes/namespaces? Minimizing use of the stl?
- s9w 6y agoKindof. Almost no standard library but it does use namespaces. (almost) no templates. Lots of pointers and arrays. Lots of explicit begin/end or push/pop functions instead of more idiomatic solutions like RAII/scope guards etc. va_ macros instead of variadic templates or fold expressions. Also while ImGUI is great and the guy follows good coding practices - it's not at all what I would recommend for learning C++. Not only is it technically not C++, but the problem it solves (GUI-Framework and immediate on top) leads to some pretty hard to follow code with a lot of hidden global state.
- iorrus 6y agoThanks that’s a great explanation
- gpderetta 6y ago> Lots of explicit begin/end or push/pop functions instead of more idiomatic solutions like RAII/scope guards etc. va_ macros instead of variadic templates or fold expressions. I'm going to have nightmares tonight.
- s9w 6y agoIt's a simple API, that's for sure. But it's pretty consistent in itself and obviously is trivial to build abstractions upon. Also makes it easy to port to other languages.
- thechao 6y agoC++ was my first language (`94?) and the one I am very passionate about; I worked on the Indiana concepts proposal & variadics for part of my dissertation, and my advisor & his colleagues designed large chunks of what would be C++11. In my opinion, the very best C++ is plain-old-C that uses modern C++ standard libraries, while carefully controlling the definition of the memory allocator for those libraries.
- Olipro 6y agoWhat use-case are you envisioning where one needs to "carefully control" the allocator for STL types? Your idea of heavenly C++ sounds like my idea of hell.
- hexane360 6y ago>Your idea of heavenly C++ sounds like my idea of hell. I'm concerned this may be the definitive C++ experience...
- ska 6y agoTrue of pretty much all "big tent" languages, I suspect.
- ajoseps 6y agoYou can use custom allocators to minimize dynamic allocation. STL now provides some of these allocators out of the box, but it still can be useful to define your own. Arena or memory pool allocators are the first that come to mind.
- spacechild1 6y agoWhile I work in a field where such things are necessary (real-time audio programming), I doubt that such things are relevant for someone just starting out with C++...
- 6y ago
- darknoon 6y agoPersonally, I think web browsers are good examples. You see integration with various platforms, abstractions on top of them, and general algorithms, generally with a consistent code style. - WebKit - Chrome
- cpeterso 6y agoYou can browse and search through the Firefox code online here: https://searchfox.org/mozilla-central/source/ https://searchfox.org/mozilla-central/source/
- aloukissas 6y agoHaven't been in cpp land for a while, but the chromium source was always my favorite good example.
- xfs 6y agoChromium's base, which is like STL but better and more feature rich, also with an excellent code browser https://source.chromium.org/chromium/chromium/src/+/master:base/ https://source.chromium.org/chromium/chromium/src/+/master:b.... Also Google's Abseil, very modern C++ patterns and containing some unexpectedly deep designs for apparently simple things. https://source.chromium.org/chromium/chromium/src/+/master:third_party/abseil-cpp/absl/ https://source.chromium.org/chromium/chromium/src/+/master:t...
- saagarjha 6y agoWebKit's equivalent, WTF: https://trac.webkit.org/browser/webkit/trunk/Source/WTF/wtf https://trac.webkit.org/browser/webkit/trunk/Source/WTF/wtf
- fsloth 6y agoThis codebase won an Oscar: https://pbrt.org/ https://pbrt.org/ https://github.com/mmp/pbrt-v3 https://github.com/mmp/pbrt-v3 That said, IMHO, there is no "clean" C++ code. There are C++ codebases that use different styles, and their "quality" more or less is context sensitive. Personally I felt the best tutorial to C++ were actually two other programming languages - Scheme and F#. Scheme drove in the concept that it's totally fine to model things based on the shape of the data and that you don't need to create type based abstractions around every thing. F# then demonstrated how a language with type system is supposed to work. The problem with C++ is that the language is so verbose that unless you have an abbreviated model in your head how a type based language can be used to solve problems in best way, you will get lost in trivial C++ minutiae. So, personally, I generally think "Am I solving a Scheme like problem or Standard ML like problem" and then try to apply C++ as simply as possible. Several academics have created a career of how to patch C++/Java/C# with concepts that make them less fragile in a collaborative context: https://en.wikipedia.org/wiki/Design_Patterns https://en.wikipedia.org/wiki/Design_Patterns https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 https://www.amazon.com/Design-Patterns-Elements-Reusable-Obj... In my opinion design patterns are not a fundamental concept, but rather provide common syntax for collaboration purposes for various patterns that are parts of language and more or less invisible in e.g. Scheme or F#. But if one is diving into C++ it's probably convenient to be familiar with these concepts.
- CyberDildonics 6y agoPBRT won a technical achievement academy award because it was a reasonably complete renderer from start to finish while being not just open source but extensively documented and explained. The source though is not a great example of modern C++ at this point. It is based heavily on inheritance and uses lots of memory allocation and virtual function calls.
- fsloth 6y agoThe source is aged a bit but a) displays a way to put together a non-trivial C++ application b) displays several extremely useful graphics related algorithms and patterns c) Is documented on a level and quality few public equal code bases reach - so get the book first and then start reading the sources
- tony 6y agoC++ build systems will be your main blocker, as they're languages in themselves. Autotools, CMake, configuring Visual Studio/etc. Easy tasks: - Challenge yourself by cloning projects reading their README and compiling/running them [1] - Port projects to other platforms (e.g. Windows-only game examples to Linux/Mac/FreeBSD) [2] Codebases I've studied [3]: sdl/graphic widgets: openttd, aseprite, nanogui(-sdl) runtime / abstraction: v8, node, protobuf, skia templates / language integration: pybind11, boost-python wrapping C: libsdl2pp (SDL2 wrapper) small: tmux-mem-cpu-load, uMario_Jakowski huge: blender Architecture / theory: https://aosabook.org/en/wesnoth.html https://aosabook.org/en/wesnoth.html, https://aosabook.org/en/audacity.html https://aosabook.org/en/audacity.html, https://aosabook.org/en/cmake.html https://aosabook.org/en/cmake.html, https://www.aosabook.org/en/llvm.html https://www.aosabook.org/en/llvm.html Books: Scott Meyers C++ books [1] It's C, but to push myself to grok build systems I tried to port tmux's autotools build system to CMake: https://github.com/tony/tmux/compare/master...tony:cmake https://github.com/tony/tmux/compare/master...tony:cmake [2] https://github.com/jakowskidev/uMario_Jakowski/pull/1 https://github.com/jakowskidev/uMario_Jakowski/pull/1 [3] https://github.com/tony/.dot-config/blob/5c59f46/.vcspull.yaml#L682-L803 https://github.com/tony/.dot-config/blob/5c59f46/.vcspull.ya...
- fsloth 6y agoOh, yes, the C++ ecosystem is horribly fragmented. But I would hardly call the build system the main blocker unless the software module under development is near trivial in complexity.
- dmacvicar 6y agoYou may enjoy browsing and reading the code of: - http://www.serenityos.org/ http://www.serenityos.org/ (Andreas Kling) - https://godotengine.org/ https://godotengine.org/ (Juan Linietsky) Those are among my favorites because of simplicity and readability vs the complexity of the domain they implement.
- tomduncalf 6y agoI'm not a C++ expert and most of my experience is with the JUCE framework so I'm a bit biased, but I think the JUCE codebase is a pretty good example of (opinonated) good practices, I often refer to it when trying to work out how to do things, even if I'm not actually using the JUCE classes/data structures: https://github.com/juce-framework/JUCE https://github.com/juce-framework/JUCE (it's a cross platform framework for developing (primarily) audio applications and plugins)
- qorrect 6y agoWow very clean. What is this syntax I don't recognize it: positionSlider.onValueChange = [this]() { seekVideoToNormalisedPosition (positionSlider.getValue()); };
- Jtsummers 6y agoLambdas. They added it a while back. [things-to-capture](params) -> return-type { function-body; } The return type is optional [0] since it can be detected automatically. The things-to-capture have a couple variants: [&foo]... Captures variable foo by reference. [foo]... Makes a copy of foo. You can also capture "everything" using [&] or [=]. Handy if you don't want to make an explicit list of captured variables. You can also mix it: [&foo, bar]... Captures foo by reference and a copy of bar. https://en.cppreference.com/w/cpp/language/lambda https://en.cppreference.com/w/cpp/language/lambda [0] Additionally, lambdas may not have a return value. Like this one: int n = 0; auto counter = [&n] () { n++; } counter(); // now n == 1
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- wcarey 6y agoGDAL - https://www.osgeo.org/projects/gdal/ https://www.osgeo.org/projects/gdal/ - is a nice codebase that features lots of hooks for extensibility, is relatively performant, and handles the sorts of complex data and algorithms you might encounter in SDR.
- ku-man 6y agoThe GDAL library is a present from the gods to the geospatial community (well, Frank Warmerdam mostly). I read the parts of the source code a while ago and the C component was fairly readable. I had troubles following the C++ code. That's the beauty of C, even if you don't use it frequently, you can still read and write half-decent code with it.
- spacechild1 6y agoI've started with C++ a couple of years ago and openFrameworks has been my entry ticket: https://github.com/openframeworks/openFrameworks https://github.com/openframeworks/openFrameworks. The code base is quite simple and readable, because it consists of several self-contained modules, many of which are just wrappers around existing libraries. For a "professional" code base, you could have a look at JUCE, which is also very modular: https://github.com/juce-framework/JUCE https://github.com/juce-framework/JUCE Both projects are written in "modern C++" (C++11 and above).
- choppaface 6y agoIf you're new to C++11, Captain Proto (particularly the kj library embedded within it-- src/kj ) is a great read: https://github.com/capnproto/capnproto https://github.com/capnproto/capnproto kj semi-re-implements several core C++11 features like Own and Maybe (actually Maybe / std::optional is still pretty new!) https://github.com/capnproto/capnproto/blob/master/c%2B%2B/src/kj/memory.h https://github.com/capnproto/capnproto/blob/master/c%2B%2B/s... Why did Kenton do this? He can speak for himself, but the core of Captain Proto is /roughly/ like a serializable / portable memory arena, so it was necessary for the design. Reading through kj and _comparing_ it with C++11 will give you some great initial insight into why both are implemented the ways they are. I'm not really advocating you use kj directly or adopt things like capnp's unique comment style, but the codebase is nevertheless very well organized and clear. Some of the older glog code is pretty nice with regards to a very vanilla and portable treatment of macros https://github.com/google/glog/tree/master/src/glog https://github.com/google/glog/tree/master/src/glog While I wouldn't necessarily recommend Boost as a model project / repo ( https://github.com/boostorg https://github.com/boostorg ), it's worth checking out to help understand why modern decisions were made the way they were.
- kentonv 6y agoOh hello. Thanks for the kind words. > Why did Kenton do this? He can speak for himself, An incomplete list of reasons: 1) At the time I started the project, a lot of things that KJ replaces, like std::optional, didn't actually exist in the C++ standard yet. 2) A lot of the stuff in the standard library is just badly designed. Take std::optional, for instance. You'd think that the whole point of using std::optional instead of a pointer would be to force you to check for null. Unfortunately, std::optional implements operator* and operator-> which are UB if the optional is null -- that's even worse than the situation with pointers, where at least a null pointer dereference will reliably crash. KJ's Maybe is designed to force you to use the KJ_IF_MAYBE() macro to unwrap it, which forces you to think about the null case. 3) A lot of older stuff in the C++ standard library hasn't aged well with the introduction of C++11, or was just awful in the first place (iostream). C++11 really changed the language, and KJ was designed entirely with those changes in mind. 4) The KJ style guide (https://github.com/capnproto/capnproto/blob/master/style-guide.md https://github.com/capnproto/capnproto/blob/master/style-gui...) adopts some particular rules around the use of const to help enforce thread safety, the specific philosophy around exceptions, and some other things, which differ from the C++ standard library's design philosophies. KJ's rules have worked out pretty well in my experience, but they break down when building on an underlying toolkit that doesn't follow them. 5) This is a silly matter of taste, but I just can't stand the fact that type names are indistinguishable from variable names in C++ standard style. 6) Because it was fun. Do these reasons add up to a good argument for reinventing the wheel? I dunno. I think it has worked well for me but smart people can certainly disagree.
- ausjke 6y agoConsidering the new C++11/14/17/20 these days you might want to focus on the new way of coding. some code for study are listed here: https://github.com/rigtorp/awesome-modern-cpp https://github.com/rigtorp/awesome-modern-cpp
- jhasse 6y agoI was pleasantly surprised when working on a patch for LyX: https://www.lyx.org/ https://www.lyx.org/ It's written in Qt, but still uses "normal" C++ for a lot of stuff.
- dedosk 6y agoMy favorites: * web browser technology chromium, v8 project * I like old school and simpler C++: Qt, KDE projects
- muststopmyths 6y agoI would pick an area you are already familiar with and then look for public codebases in that field. Otherwise it can be hard to just read C++ code and figure out the organization/abstractions. To generalize: - Google software like protobufs and chrome are good examples of accepted C++ practice in the general software industry. It goes a bit overboard in the C++-iness for my taste, but that's just a personal thing. - For game engines, Unreal Engine 4 is good example of pretty well-organized large C++ codebase. For size and complexity of the beast, it is not hard to read the code. Understanding the overall structure depends on how deep you are already into games. - There are some games over the years that have released their source code. I consider Monolith's games (F.E.A.R, No One Lives Forever 2) to be pretty well-organized C++ code. They're very out of date now, but you can apply newer C++ features to their basic structure and still come away with decent code. To learn C++, I would start with your own C code and the morph it in the following ways: - Use C++ objects to represent functionality boundaries and data abstractions. You probably have a bunch of structs and functions that operate on them. Convert those to C++. - Start using destructors to automatically clean up objects. Read up on RAII patterns. - Use smart pointers instead of dynamically allocating/freeing memory with malloc/new/free/delete. After these basics, you can branch out into exploring more in depth with templates, fancy C++17/20 features etc. Don't try to use all the features and capabilities at the outset. You can end up with a codebase you won't want to read in a year, let alone other people on your project. I've seen massive, unreadable templated code because someone got a shiny new template hammer and banged away at every problem as a nail.
- tcbawo 6y agoSound advice. I would advise designing with unique pointers first and minimize shared pointers where possible. Shared pointers have a smell. Smart pointers have reference counting overhead. Unique pointers communicate ownership, while smart pointers communicate lack of ownership. I would also recommend using an IDE with decent tooling. C++ is insanely hard to parse. If you go so template/macro crazy that you confuse your IDE context parser, you will most certainly confuse other people reading your code.
- mehrdadn 6y agoYou're in for a wild ride. C++ takes forever to learn (basically, it never ends) and people have VERY different senses of what "clean" C++ code is like. And for that matter, even the same person might write in different styles depending on the situation. And the same exact style might be terrible for one situation but awesome for another. With all that said, one "good" kind of codebase to at least know (even if you can't emulate it) is the kind of codebase that is modeled after the C++ standard library. Some Boost libraries (not all!) are great examples of this. Probably the best example I can think of off the top of my head is Boost.Container: https://www.boost.org/doc/libs/1_74_0/boost/container/vector.hpp https://www.boost.org/doc/libs/1_74_0/boost/container/vector... Note that this does not mean you should write code like this for your applications, though. Boost is heavyweight with the templates/headers/macros and these classes are meant to be extremely generic. Your application-level code does not necessarily need to meet the same types of constraints, and it's just not worth the effort in most cases (as well as being slower to compile). But if you can write this kind of code when it's warranted, it ends up being very high-quality. (Some parts of this involve a lot of difficult work, like paying attention to exception-safety, that is often unnecessary. Other parts are quite simple and well worth picking up, e.g. liberal use of typedefs. And everything else in between.) A more typical example of a codebase might be some of wxWidgets, e.g.: https://github.com/wxWidgets/wxWidgets/blob/v3.1.4/src/generic/listctrl.cpp https://github.com/wxWidgets/wxWidgets/blob/v3.1.4/src/gener... It's not in the style of the standard library (so you won't find it to be as generic, exception-safe, etc.) but it's pretty decent.
- jstimpfle 6y ago> Probably the best example I can think of off the top of my head is Boost.Container: > https://www.boost.org/doc/libs/1_74_0/boost/container/vector https://www.boost.org/doc/libs/1_74_0/boost/container/vector... Which I find absolutely hilarious. Thousands of lines of boilerplate for something as simple as an dynamically resizable array. Only for the _header_ which has to be included at each location that uses a vector either directly or indirectly. These are the kinds of things that prevent me from touching C++.
- fsloth 6y ago
- anonymousGeese 6y agoYou should checkout the Haiku operating system; some source files in there are outdated and haven't been touched in 20 years, but other than that, it is seriously very consistent and even eye-candy-ish. https://github.com/haiku/haiku https://github.com/haiku/haiku
- palotasb 6y agoI recommend the LLVM source code. I've worked a bit with it implementing toy compilers and using LLVM as a backend for generating x86/SPARC object code. Just compiling it is a nice exercise if you're new to C++ and CMake (as I was, then). I would start by reading the LLVM Programmer's Manual [prog man] and the LLVM Coding Standards [code stand] and looking up how the code they reference and the examples are implemented and how they interact with each other. You can browse the code in the LLVM Mirror Git repository [llvm-git] or the cross-referenced Doxygen [llvm-doxy] (has very useful links!). If you're willing to spend the time it might be worth setting up the codebase in your IDE of choice with the proper integrations to be able to browse and cross-reference the source code there. There is a lot to learn especially from the Important and useful LLVM APIs and Picking the Right Data Structure for a Task (and the corresponding code) in the Programmer's Manual. The data structures under llvm/ADT could be especially useful to look at. They are good generic data structures that you may even want to directly reuse in your own project, but they are much easier on the eyes and closer to what you and I would want to see in our own codebases than the source code of the standard library or the Boost data structures. [prog man]: https://releases.llvm.org/4.0.1/docs/ProgrammersManual.html https://releases.llvm.org/4.0.1/docs/ProgrammersManual.html [code stand]: https://releases.llvm.org/4.0.1/docs/CodingStandards.html https://releases.llvm.org/4.0.1/docs/CodingStandards.html [llvm-git]: https://github.com/llvm-mirror/llvm https://github.com/llvm-mirror/llvm [llvm-doxy]: http://llvm.org/doxygen/modules.html http://llvm.org/doxygen/modules.html PS. The Coding Standards will contain a lot of subjective stuff that makes sense inside LLVM for consistency but you don't want to adopt verbatim into an existing (maybe not even a green field) project, like naming variables with Capital letters. You can skim these parts, but it might be useful to know about the existence of these types of issues.
- plibither8 6y agoFor a simple command line program, I created 2048.cpp: https://github.com/plibither8/2048.cpp https://github.com/plibither8/2048.cpp. It's gained quite some popularity (GitHub tweeted about it [1]), and the codebase has improved and grown all thanks to a new maintainer. [1]: https://twitter.com/github/status/1017094930991370240 https://twitter.com/github/status/1017094930991370240 Also on HN: https://news.ycombinator.com/item?id=17897283 https://news.ycombinator.com/item?id=17897283 PS: A fork of 2048.cpp was even used as a demo at CppCon 2020 (https://www.youtube.com/watch?v=HrOEyJVU5As https://www.youtube.com/watch?v=HrOEyJVU5As)
- jeffbee 6y agoI recommend Abseil. They have a good style that uses some modern C++ features but not the kitchen sink. Example you could start right here: https://github.com/abseil/abseil-cpp/blob/master/absl/strings/cord.h https://github.com/abseil/abseil-cpp/blob/master/absl/string... LevelDB is good reading, too.
- dragontamer 6y agohttps://github.com/official-stockfish/Stockfish https://github.com/official-stockfish/Stockfish
- stagger87 6y agoI suggest the Doom3 source code. https://github.com/TTimo/doom3.gpl https://github.com/TTimo/doom3.gpl I find it to be extremely readable, and it has a C with classes approach that I tend to gravitate towards when I'm developing in C++. It is not an example of "modern C++".
- jstimpfle 6y agoSecond that, it's beautiful.
- tayistay 6y agoNot terribly impressed. This wouldn't pass my code review: https://github.com/TTimo/doom3.gpl/blob/aaa855815ab484d5bd095f347163194ac569abcc/neo/renderer/MegaTexture.cpp#L748 https://github.com/TTimo/doom3.gpl/blob/aaa855815ab484d5bd09... Function is 200 lines long, with 8 or so levels of nesting. Also "goto breakout" To address the objections below, the function reads from a file into a pixel buffer. It's not some tricky in-place update. That's a great candidate for a more functional style. Here's more ick: https://github.com/TTimo/doom3.gpl/blob/aaa855815ab484d5bd095f347163194ac569abcc/neo/game/physics/Physics_Player.cpp#L168 https://github.com/TTimo/doom3.gpl/blob/aaa855815ab484d5bd09... Surely that could be factored better. Down-voters go read Carmack's own article: https://gamasutra.com/view/news/169296/Indepth_Functional_programming_in_C.php https://gamasutra.com/view/news/169296/Indepth_Functional_pr... I think it's funny that people disagree here. This is exactly the stuff a modern linter would flag in an automated code review. Sure enough, here's a linter. I think this is essentially the same codebase: https://lgtm.com/projects/g/Edgarins29/Doom3/context:cpp https://lgtm.com/projects/g/Edgarins29/Doom3/context:cpp "Code quality: D" (on an A-F scale) And by the way, I have the utmost respect for Carmack. I just wouldn't hold up this codebase as great.
- Guzba 6y agoCounter argument: http://number-none.com/blow/john_carmack_on_inlined_code.html http://number-none.com/blow/john_carmack_on_inlined_code.htm...
- 6y ago
- eugenekolo 6y agoAOSP (Android Open Source Project) and Chromium (Open source Chrome) are good, because they have well defined C++ coding styles that prohibit a lot of unmaintainable/unreadable things.
- bitigchi 6y agoHaiku: https://git.haiku-os.org/haiku/tree/ https://git.haiku-os.org/haiku/tree/ It's written in C++, has strict coding guidelines, and mostly free of bloat.
- rramadass 6y agoSince C++ is a "Multi-Paradigm" language your study of C++ code should include the various different expressions of the language. Also it is best if you can have a book explaining and walking you through the codebase. To that end i can suggest the following from my own experience; * To study OO expression of C++ via Class libraries/Frameworks i recommend a study of "Microsoft Foundation Classes (MFC) library" paired with the book MFC Internals. The code is available with the installation of Visual Studio. * P.J.Plauger's The Standard C Library and The C++ Standard Template Library(with Alexander Stepanov, Meng Lee and David Musser) will teach you excellent C and C++ Generic programming skills. Code available with the standard C++ toolchain installation. * The Boost libraries paired with the book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond. * The FXT library of Algorithms by Jorg Arndt (https://www.jjj.de/fxt/fxtpage.html https://www.jjj.de/fxt/fxtpage.html) along with its book Matters Computational for writing optimized C++ code. I would also suggest reading the following two classics to learn designing in C++; * Multi-Paradigm Design for C++ by James Coplien. * Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples by Barton and Nackman.
- ryansmccoy 6y agoIf interested in Financial Markets, Quantlib is interesting. https://github.com/lballabio/QuantLib https://github.com/lballabio/QuantLib Also, there is a book which describes the different patterns used: https://leanpub.com/implementingquantlib https://leanpub.com/implementingquantlib
- markpapadakis 6y agohttps://medium.com/@markpapadakis/interesting-codebases-159fec5a8cc https://medium.com/@markpapadakis/interesting-codebases-159f... In addition to those I highly recommend studying ClickHouse’s codebase. There are brilliant design and engineering bits everywhere. I learned more from studying this codebase than most other I can think of, especially with regards to templates meta-programming ( I learned about “template template parameters” from coming across extensive use of those there ). It’s actually somewhat challenging to grok what’s going on — but it is worth pushing through until you “get it”.
- shepik 6y agoYep, i second the clickhouse suggestion. Much more easier to understand than, say, mongodb or mysql codebases.
- blinkingled 6y agoC++ - for people who just can't get enough complexity, and surprises.
- yonatano 6y agoKeith Schwarz maintains an "Archive of interesting code" which has lots of C++ implementations: https://www.keithschwarz.com/interesting/ https://www.keithschwarz.com/interesting/
- ourcat 6y agoNot so long ago I decided I wanted to learn some C++ and ended up getting some cheap micro controllers and starting with Arduinos and learning from the examples in various libraries. Now I'm having a lot of fun, still learning, while programming the ESP8266 and especially the ESP32 (via PlatformIO). Playing with Wifi and Bluetooth too. The best thing in my view about learning things with micro controllers is the 'tangible' result. Seeing things happen or move. (or not! and why.) I thoroughly recommend it, along with all the other responses here.
- postit 6y agoEnvoy is one of the best samples for networking I've had to deal in my career.
- arximboldi 6y agoThat's a tricky question. Large C++ codebases often have a lot of "legacy" that does not necessarily reflect the best practices. A couple of years ago I wrote a text-editor to have a realistic example of what I consider a nice modern architecture using immutable data-structures. In the README there is also a link to a talk where I cover some of the design and structure: https://github.com/arximboldi/ewig https://github.com/arximboldi/ewig Libraries that it uses: https://github.com/arximboldi/immer https://github.com/arximboldi/immer https://github.com/arximboldi/lager https://github.com/arximboldi/lager
- bertr4nd 6y agoOne of the reasons it’s hard to talk about clean C++ codebases is that there’s a huge range of possible complexity. The gap between “Solve a particular problem” and “provide a generic library” is very big. Template metaprogramming deservedly gets a lot of the blame, but implicit heap management via constructors/destructors is also pretty hard to follow. The upshot is that “professional grade” C++ is often impenetrable (I tried to understand the implementation of boost::intrusive_list once. Yikes.) LLVM is often cited as a very clean codebase and I think that holds up. Facebook’s folly is another good one (although it occasionally dives into template metaprogramming madness). Hopefully I’ll be forgiven for also plugging a few projects I used to work on, that might hit a sweet spot between utility and code complexity: - Glow, a compiler for neural networks: https://github.com/pytorch/glow https://github.com/pytorch/glow - ReDex, a bytecode optimizer for Android: https://github.com/facebook/redex https://github.com/facebook/redex There was a nice blog post a few years back called “c++11 is a scripting language” that is unfortunately offline now; it did some task like reading lines from a file and sorting them, and it wasn’t dramatically more complicated than the same thing in Python. It’s worth doing a few of those kinds of exercises to get a feeling for the language.
- gumby 6y ago> I tried to understand the implementation of boost::intrusive_list once. Yikes. To be fair library code, especially library code that's supposed to run on a huge number of compilers and platforms, must include support for a ton of weirdo special cases which ultimately render it unreadable to someone not steeped in it. It also has to handle weird corner cases most developers might not think of, either because it's just a weird corner of the standard or because it might commonly be, say, embedded in some other structure or used in an unusual template expansion which would imply non-obvious constraints. This BTW is true of any language. By contrast: I wrote a small lock-protected container template used in a local code base. It's short, fast and easy to use. Also easy to understand if you bother to read the code (but it's so easy to use, why bother). But there's a huge tradeoff: it doesn't act completely like a regular container; it only handles cases we care about in our code base and only works on the three compilers we care about. There is zero interest in implementing a more general solution. When this object doesn't work, sometimes we extend it and sometimes we change the caller. So which would be a better example to read? I'd argue: neither.
- in42 6y agoYou can look at the pybind11 (https://github.com/pybind/pybind11 https://github.com/pybind/pybind11) codebase. It is a library for generating python bindings for C++ code. It uses latest C++17 and does quite a lot of template metaprogramming to generate the bindings.
- deleted 6y ago[deleted]
- sneeuwpopsneeuw 6y agoOne thing that helped me to get some insides in c++ was the old Command and Conquer source code from the 90's https://github.com/electronicarts/CnC_Remastered_Collection https://github.com/electronicarts/CnC_Remastered_Collection Jason Turner has multiple videos where he takes this old code and transforms it to more modern cpp code https://www.youtube.com/watch?v=Oee7gje-XRc https://www.youtube.com/watch?v=Oee7gje-XRc
- gioscarab 6y agoSee PJON, it is also loosely related to SDRs https://github.com/gioblu/PJON https://github.com/gioblu/PJON
- jlrubin 6y agohttps://github.com/bitcoin/bitcoin https://github.com/bitcoin/bitcoin could be fun to explore some modules (email me if you want some guidance). I wouldn't say it's particularly "clean", given the constraints on the project, but it does do a lot of things that are interesting from a security/DoS perspective. There are even some SDR related work being done recently for alternative relays!
- jlrubin 6y agoA few sub-projects you might be into: WSPR: https://youtu.be/QkYXPJMqBNk?t=4974 https://youtu.be/QkYXPJMqBNk?t=4974 Blockstream Sat: https://github.com/Blockstream/satellite https://github.com/Blockstream/satellite
- MorganGallant 6y agoThis may have been mentioned already, but the open-sourced LevelDB codebase is great. Original authors are Jeff Dean and Sanjay Ghemawat, so you know it's going to be really well written. https://github.com/google/leveldb https://github.com/google/leveldb
- staticfloat 6y agoI have always found magnum to be a very nicely constructed C++ codebase: https://github.com/mosra/magnum https://github.com/mosra/magnum The abstractions that are built up within that codebase feel very clean, like they get out of your way so that you can be productive, without drowning you in syntax.
- diehunde 6y agoI spent the last month studying LevelDB's codebase without much knowledge of C++. Learnt a lot during the process.
- latenightcoding 6y agohttps://github.com/facebook/folly https://github.com/facebook/folly https://github.com/ziglang/zig https://github.com/ziglang/zig
- signaru 6y agoNot a codebase, but a book (readable online). Would be helpful for identifying "good" OOP patterns in other code you may encounter: https://gameprogrammingpatterns.com/ https://gameprogrammingpatterns.com/ Examples are in C++ and the prose is also far more friendly than standard academic texts.
- UncleOxidant 6y agoNarrowing things down a bit, I'm wondering if there are any good C++17+ code bases to read? I see a lot of recommendations for C++11 codebases here, but a lot has changed since then.
- pooya13 6y agoI suggest chai script: https://github.com/ChaiScript/ChaiScript https://github.com/ChaiScript/ChaiScript I haven’t looked at it but from Jason Turners’ videos I know he uses the modernize and cpp core guidelines checks with clang tidy on it so it should be modern c++.
- oscargrouch 6y agoI had a phase where i digged into a lot of codebases (with a bunch of C++) and i've learned to admire the way the code is layout in some of them, giving composing state in some of them is very hard to do it right. In my experience, the stuff in C++ from Microsoft and Google are great resources to learn, so i would give a especial mention to (in order of C++ awesomeness): Dart VM Chakra VM V8 VM Chrome LevelDb WebKit (*) Doom 3 engine * - Doom 3 is not very modern by today standards, but the way the code is composed, the things relate among themselves, etc, are a great resource of learning. * - Didnt dig much into the most modern stuff from Mozilla, so i dont know how it is actually. Back in the day, there were a lot of legacy from their older codebases, so i dont now how the more modern stuff are, but im almost sure they might look great.
- cmrdporcupine 6y agoLLVM. Abseil. I work in Chromium all day long, so I'd like to say that, but it's also huge and has... complexities.
- SnowflakeOnIce 6y agoLLVM is good but highly idiosyncratic. A lot of complexity shows up there from doing things like building and using a custom RTTI mechanism.
- cmrdporcupine 6y agoIt is also huge. But so is Chromium.
- arriu 6y agoGames might be an interesting one to look at because they have a little bit of everything going on (physics, math, rendering, cross platform abstractions, window management, system calls, file management, memory management, etc...) Take a look at these: https://github.com/FrictionalGames/AmnesiaTheDarkDescent https://github.com/FrictionalGames/AmnesiaTheDarkDescent https://github.com/FrictionalGames/PenumbraOverture https://github.com/FrictionalGames/PenumbraOverture
- crocodiletears 6y agoI can't speak Frictional's code quality, but historically released titles tend to be a tangle of hacks and short-term decisions that hammer things into working or being performant, coming at the expense of future developers and correctness. I do agree that the field is full of great code to reference, though. I'm a huge fan of Godot's codebase. It's well written, and easily understood both architecturally, and in-method. https://github.com/godotengine/godot https://github.com/godotengine/godot
- Ace17 6y agoYou can't have a unified opinion here. There are some pretty good public game codebases (Penumbra/HPL, Quake I/II/III, Doom I/III), there are some okay ones (RedAlert), there are also pretty awful ones (Duke3D, Descent). Note that this seems to be completely independent from whether the game is good or not!
- ncmncm 6y agoWhen I looked at Godot I saw all pre-C++11, and everything done the hard way. Did I look in the wrong place?
- crocodiletears 6y agoI wouldn't call it the hard way, but it's certainly pre-C++11. My understanding is that the project's lead programmer insists on using older standards for the sake of portability.
- oandrew 6y agoClickHouse has very clean and modern C++ codebase. https://github.com/ClickHouse/ClickHouse https://github.com/ClickHouse/ClickHouse
- emteycz 6y agoSerenityOS
- mrmrcoleman 6y agoQuake III is always fun reading: https://github.com/id-Software/Quake-III-Arena https://github.com/id-Software/Quake-III-Arena
- deleted 6y ago[deleted]
- jeff-davis 6y agoI don't do a lot of C++, but when I want to see how to do something right (or at least better than I would), I look at LLVM.
- abrolhos 6y agoJust a suggestion... I cannot attest for the code quality of the projects on the link below, but I find it easier to start learning from smaller code bases. So when you have a chance you could take a look at this link that lists one-to-two files libraries: https://github.com/nothings/single_file_libs https://github.com/nothings/single_file_libs I think I came across the link above here on HN a couple of weeks ago. I also study some of the libs from here: https://github.com/fffaraz/awesome-cpp https://github.com/fffaraz/awesome-cpp. Currently I'm going trough the libs for parsing CSV files. Of them, I find this one particularly interesting: https://github.com/vincentlaucsb/csv-parser https://github.com/vincentlaucsb/csv-parser. Because of well-commented files. I hope it helps.
- abrolhos 6y agoOh, almost forgot. Another suggestion is to review C++ implementations of those designs you're already familiar with. I'm also looking into Inversion of Control/Dependency injection containers. And never forget to look at C++ Core guidelines: https://isocpp.org/guidelines https://isocpp.org/guidelines
- artagnon 6y agoHere are a couple of expertly-written C++17/C++20 repositories: https://github.com/hanickadot/compile-time-regular-expressions https://github.com/hanickadot/compile-time-regular-expressio... https://github.com/nlohmann/json https://github.com/nlohmann/json If you've not written C++ code before, it can take a while to catch up with the latest developments in C++23. Start with C, and learn these, in approximately the specified order: 1. lvalue references. 2. Constructors, destructors, and inheritance. 3. Annotations such as const and noexcept on members. 4. Simple type templates, and value templates. 5. constexpr, std::move, and rvalue references. 6. Type traits and std::enable_if. 7. Concepts. Once you learn the core language features, learning the various data structures/algorithms in `std` should just be a matter of looking them up in cppreference, and using them over and over again. Good luck.
- giancarlostoro 6y agoThe JSON library is impressive: https://github.com/nlohmann/json#examples https://github.com/nlohmann/json#examples
- ChuckMcM 6y agoThis is excellent. FWIW I bought and read "C++ Crash Course" by Lospinso. I found that tremendously helpful with his approach of "assuming you really know C [I do], here is C++" and can easily recommend his book for anyone on this path. That said, I like your ordering too. The other confounding factor is that I have also written a lot of Java code (both during the development of the language and afterward for my column in Javaworld) which I really enjoyed, but it too "fixes" some things which James disliked about C++ (and as a long time C programmer I understood quite well). As a learning experience, this journey has been confounding, enlightening, and painful in equal measures :-)
- ncmncm 6y agoPeople who come to C++ from Java frequently bring with them Java Disease. If you find yourself reaching for std::shared_ptr and virtual functions more often than once in a blue moon, you are suffering from Java Disease, and are writing bad code. Anything that seems to be something Java "fixed" is a thing they failed to understand. You will have to unlearn those, along with myriad bad C habits, many of which you don't know you have. It takes sharp observation to catch them.
- hartem_ 6y agoApache Mesos has a very solid, clean and well maintained code base (https://github.com/apache/mesos https://github.com/apache/mesos). It’s a massively scalable distributed system that has been running in production for many years at Twitter, Apple, Netflix and other places (more recently it’s being replaced by Kubernetes, but that’s beside the point of this thread). Mesos is interesting as a whole but it also has some parts that are notoriously hard to get right (like their Paxos implementation). It also contains an RPC library that implements an actor model and uses futures and promises (https://github.com/apache/mesos/tree/master/3rdparty/libprocess https://github.com/apache/mesos/tree/master/3rdparty/libproc...), as well as a header-only utility library called Stout (https://github.com/apache/mesos/tree/master/3rdparty/stout https://github.com/apache/mesos/tree/master/3rdparty/stout) with a lot of useful functions.
- claytongulick 6y agoThe QuickJS code base is a joy to read.
- tebeka 6y agoApache arrow
- deleted 6y ago[deleted]
- kartayyar 6y agoI suggest looking at some of Google's open sourced projects. - Abseil: https://github.com/abseil/abseil-cpp https://github.com/abseil/abseil-cpp https://cs.opensource.google/abseil https://cs.opensource.google/abseil - Tensorflow: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/example https://github.com/tensorflow/tensorflow/tree/master/tensorf... https://cs.opensource.google/tensorflow https://cs.opensource.google/tensorflow - Chrome https://chromium.googlesource.com/chromium/src.git/+/refs/heads/master https://chromium.googlesource.com/chromium/src.git/+/refs/he... https://source.chromium.org/chromium https://source.chromium.org/chromium There is a very high bar for C++ code quality at Google, and also a published style / best practices guide as well as a code search engine to browse the code more easily.
- ncmncm 6y agoBut be careful about picking up Googlisms. Google's allergy to exceptions pollutes their designs. Any class with default constructor, Init, and Deinit is badly polluted.
- boryas 6y agoLLVM e.g. SmallVector: https://llvm.org/doxygen/SmallVector_8h_source.html https://llvm.org/doxygen/SmallVector_8h_source.html Folly e.g. https://github.com/facebook/folly/tree/master/folly/logging https://github.com/facebook/folly/tree/master/folly/logging, https://github.com/facebook/folly/blob/master/folly/concurrency/ConcurrentHashMap.h https://github.com/facebook/folly/blob/master/folly/concurre..., https://github.com/facebook/folly/tree/master/folly/executors https://github.com/facebook/folly/tree/master/folly/executor...
- ncmncm 6y agoMost code you will run across is written in an ancient version of the language. Most of the code suggested in this thread is that. Modern C++ looks very, very different from C, and even more different from Java. So, if you see code that looks like one of those, you know it is not a thing to emulate. Certain companies, notably Mozilla and Google, have extremely peculiar coding standards that badly warp how code has to be written for them. You do not want to emulate that code. If you see classes with "Init" and "Deinit" members, and constructors that don't do anything, you know you are in a dark back alley headed for a world of suffering. If you see code that looks like it might as well be C, it's probably bad code. Modern C++ is a very, very different language from C. Most of your C habits, if you have any, are bad C++ habits that you will need to work hard to unlearn. In particular, if you handle naked pointers much, you are Doing It Wrong. If you see code organized like Java, full of shared_ptr and virtual functions, it's certainly bad code. (I think Dropbox just published a big library that was virtual functions from top to bottom. Shiver.) We call that Java Disease. Inheritance and virtual functions are occasionally useful, as pure mechanism, but not as an organizing principle. Modern C++ code works with values more than pointers or references, and prefers to pass objects by move over by reference. If you actually see allocations, and particularly deallocations, in top-level code, it is very likely to be bad code.
- grishka 6y agoWebRTC is okayish imo but be prepared for tons of complex templates.
- brogrammer2019 6y agoMaybe your C++ for Professionals book? Which has hundreds of C++ code examples to read https://books.goalkicker.com/CPlusPlusBook https://books.goalkicker.com/CPlusPlusBook
- olliej 6y agoThe webkit codebase is fairly clean and modern, and is a good example of structure across a gigantic code base
- zonovar 6y agoHere's my pick for you. It's a very well writtern and degined piece of code. It's clean and well documented. - SFML is a simple, fast, cross-platform and object-oriented multimedia API. It provides access to windowing, graphics, audio and network. https://github.com/SFML/SFML https://github.com/SFML/SFML
- junon 6y agohttps://github.com/skypjack/entt https://github.com/skypjack/entt Amazing codebase by an amazing developer and maintainer.
- known 6y agohttps://rosettacode.org/wiki/Category:C%2B%2B https://rosettacode.org/wiki/Category:C%2B%2B
- blueprint 6y agohttps://github.com/vtnerd/monero-lws https://github.com/vtnerd/monero-lws
- timkofu 6y agoTensorflow https://github.com/tensorflow/tensorflow https://github.com/tensorflow/tensorflow