Skip to main content

dev-cpp

C++ learning resources

[[TOC]]

New Project Templates

2023-05-17 cpp-best-practices/cmake_template

"cmake_template" is a C++ Best Practices GitHub template designed for quick C++ project setups. Currently undergoing a major update, it enables Address Sanitizer, Undefined Behavior Sanitizer, treats warnings as errors, and performs static analysis using clang-tidy and cppcheck. It uses CPM for dependencies and provides a basic CLI example, testing examples, and a large Github action testing matrix. It requires cmake and a compiler to use. The project includes a simple usage example of FTXUI, featuring a game.

2023-05-17 bsamseth/cpp-project: Boiler plate template for C++ projects, with CMake, Doctest, Travis CI, Appveyor, Github Actions and coverage reports.

This is a boiler plate for C++ projects. What you get:

image-20230519215754359

Books

The 'tour' is a quick (254 pages + index, historical information, etc.) tutorial overview of all of standard C++ (language and standard library) at a moderately high level for people who already know C++ or at least are experienced programmers. It covers C++20 plus a few likely features of C++23.

60 Dirty tips for dirty developers ;)

Almost a book!

... and the list goes on and on

C++ Interactive tutorials

These two are very good beginner resources:

C++ Awesome Lists

A curated list of awesome C++ (or C) frameworks, libraries, resources, and shiny things. Inspired by awesome-... stuff.

image-20231103173812216

A curated list of awesome tools, libraries, and resources for the Qt framework.

image-20231103173928968

image-20231103174233899

C++ Other learning resources

image-20240208182036869

image-20231230114303365

Amazing effort to visualize how the standard algorithms in C++ work.

image-20231230120034549

Google's Introduction to Programming and C++
This online tutorial continues with more advanced concepts - please read Part III. Our focus in this module will be on using pointers, and getting started with objects.

2023-08-14 Performance Ninja -- Data Packing Intro - YouTube

2023-08-14 GitHub - dendibakh/perf-ninja: This is an online course where you can learn and master the skill of low-level performance analysis and tuning. Performance Ninja Class This is an online course where you can learn to find and fix low-level performance issues, for example CPU cache misses and branch mispredictions. It's all about practice. So we offer you this course in a form of lab assignments and youtube videos. You will spend at least 90% of the time analyzing performance of the code and trying to improve it.

image-20230813230433926

C++ CHEATSHEET

C / C++ and GUI

2023-10-28 Skia

C++ Skia is an open source 2D graphics library which provides common APIs that work across a variety of hardware and software platforms. It serves as the graphics engine for Google Chrome and ChromeOS, Android, Flutter, and many other products. https://skia.org/docs/user/modules/canvaskit/

image-20231103174340719

TTY UI

  • CursedGL A C notcurses-based software rasterizer inspired by OpenGL 1.X that renders directly to the terminal.
  • FINAL CUT C++ library for creating terminal applications with text-based widgets
  • FTXUI 💻 C++ Functional Terminal User Interface. ❤️
  • ncurses A classic C library with bindings for many languages

Codding Style

  • 2022-10-17 C++ Core Guidelines by Bjarne Stroustrup, Herb Sutter

    This is a set of core guidelines for modern C++ (currently C++20 and C++17) taking likely future enhancements and ISO Technical Specifications (TSs) into account. The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.

  • 2022-10-02 Google C++ Style Guide

Articles

  • 2023-06-24 Make your programs run faster by better using the data cache - Johnny's Software Lab

    It covers the following topics and tips:

    • The concept and importance of cache memory and how it compensates for the difference in speed between processor and main memory.
    • The principles of temporal and spatial locality, which govern the behavior of real-world programs and affect the cache performance.
    • The tips and rules for better exploiting the data cache in different scenarios, such as:
      • Using arrays of classes or structs instead of values, to increase the cache utilization and reduce the cache misses.
      • Aligning the starting address of the array and the class data to the cache line size, to avoid splitting the data across multiple cache lines and to optimize the cache access.
      • Performing loop interchange on matrices, to move the loop over the innermost position and to eliminate column-wise accesses, which are costly for the cache.
      • Avoiding padding in classes and structs, to make sure they are correctly aligned and to reduce the cache overhead.
      • Sorting the variables in the declaration of the classes by size from largest to smallest, to guarantee that the compiler will not insert any padding and to optimize the cache access.
    • The tools and references available to help with the data cache optimization, such as pahole and StuctLayout, which can help with exploring and visualizing the paddings in the classes.
  • Modern C++ for C Programmers: part 1 - Bert Hubert's writings

    Welcome to part 1 of Modern C++ for C Programmers, please see the introduction for the goals and context of this series.

    In this part we start with C++ features that you can use to spice up your code ’line by line’, without immediately having to use all 1400 pages of ‘The C++ Programming Language’.

    Various code samples discussed here can be found on GitHub.

  • 2022-03-05 Beginner's Guide to Linkers

    This article is intended to help C & C++ programmers understand the essentials of what the linker does. I've explained this to a number of colleagues over the years, so I decided it was time to write it down so that it's more widely available.

  • 2022-10-16 What is Primitive Obsession and How Can we Fix it? HackerNoon

    Primitive obsession is a code smell in which primitive data types are used excessively to represent your data models. The problem with primitives is they are very general. For example, a string could represent a name, an address, or even an ID. Why is this a problem?

  • 2022-10-16 Lippincott Pattern C++

    My coworkers at the then-customer were nice and open minded people so they didn't bridle at that, on the contrary, they were eager to change it and asked for advice. I simply said that they should google for the "Lippincot Pattern" and thought the matter were settled.

  • 2023-10-13 Embedded C/C++ Unit Testing with Mocks | Interrupt

    Writing a unit test from scratch for an embedded software project is almost always an exercise in frustration, patience, and determination. This is because of the constraints, as well as breadth, of embedded software. It combines hardware drivers, operating systems, high-level software, and communication protocols and stacks all within one software package and is usually managed by a single team. Due to these complexities, the number of dependencies of a single file can quickly grow out of control.

    image-20231103175806064

Regular Expressions

Cross-platform testing

Optimization

2023-08-01 💡 Agner Fog

According to ChatGPT: Agner Fog is a Danish professor known for his work in cultural selection theory, optimization methods, and system development methods. He holds a PhD in Operations Research and has a diverse educational background including sociology, statistics, and computer science.

One of his main contributions to the field of computer science is his development of CPU dispatcher software and comprehensive documentation of instruction latencies and throughputs for various CPU models. His optimization guides and tools are popular among performance-oriented programmers.

In the field of social sciences, he has developed a theory of cultural selection, which is similar to biological evolution but acts on cultural phenomena such as norms, traditions, language, technology, and art.


Software optimization resources

Optimization manuals

Optimizing software in C++: An optimization guide for Windows, Linux and Mac platforms

This is an optimization manual for advanced C++ programmers. Topics include: The choice of platform and operating system. Choice of compiler and framework. Finding performance bottlenecks. The efficiency of different C++ constructs. Multi-core systems. Parallelization with vector operations. CPU dispatching. Efficient container class templates. Etc.

File name: optimizing_cpp.pdf, size: 1838972, last modified: 2023-Jul-01. Download.

The microarchitecture of Intel, AMD and VIA CPUs: An optimization guide for assembly programmers and compiler makers

This manual contains details about the internal working of various microprocessors from Intel, AMD and VIA. Topics include: Out-of-order execution, register renaming, pipeline structure, execution unit organization and branch prediction algorithms for each type of microprocessor. Describes many details that cannot be found in manuals from microprocessor vendors or anywhere else. The information is based on my own research and measurements rather than on official sources. This information will be useful to programmers who want to make CPU-specific optimizations as well as to compiler makers and students of microarchitecture.

File name: microarchitecture.pdf, size: 2472395, last modified: 2023-Jul-01. Download.

C++ vector class library

This is a collection of C++ classes, functions and operators that makes it easier to use the the vector instructions (Single Instruction Multiple Data instructions) of modern CPUs without using assembly language. Supports the SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX, AVX2, FMA, XOP, and AVX512F/BW/DQ/VL instruction sets. Includes standard mathematical functions. Can compile for different instruction sets from the same source code. Description and instructions. Message board. Source on Github. Nice little instruction video by WhatsaCreel.

Latest release.

image-20230801220021917

2023-08-05 Book Data-Oriented Design Richard Fabian

Online release of Data-Oriented Design : This is the free, online, reduced version. Some inessential chapters are excluded from this version, but in the spirit of this being an education resource, the essentials are present for anyone wanting to learn about data-oriented design. Expect some odd formatting and some broken images and listings as this is auto generated and the Latex to html converters available are not perfect. If the source code listing is broken, you should be able to find the referenced source on github. If you like what you read here, consider purchasing the real paper book from here, as not only will it look a lot better, but it will help keep this version online for those who cannot afford to buy it. image-20230805004022297

DOD

2023-07-25 Getting Friendly With CPU Caches

When a CPU needs to access a piece of data, the data needs to travel into the processor from main memory.

The architecture looks something like this:

Figure 1: CPU Cache

img

Figure 1 shows the different layers of memory a piece of data has to travel to be accessible by the processor. Each CPU has its own L1 and L2 cache, and the L3 cache is shared among all CPUs. When the data finally makes its way inside the L1 or L2 cache, the processor can access it for execution purposes. On Intel architectures the L3 cache maintains a copy of what is in L1 and L2.

Performance in the end is about how efficiently data can flow into the processor. As you can see from the diagram, main memory access is about 80 times slower than accessing the L1 cache since the data needs to be moved and copied.

Note: Memory Performance in a Nutshell: The data is from 2016 but what’s important are the latency ratios which are pretty constant.

2023-08-06 CPP How branches influence the performance of your code and what can you do about it? - Johnny's Software Lab

from 2023-08-06 Programming Digest - A newsletter about programming and technology

2023-08-07 CPP Crash course introduction to parallelism: SIMD Parallelism - Johnny's Software Lab

2023-08-07 CPP Make your programs run faster by better using the data cache - Johnny's Software Lab

2023-08-07 CPP Bit Twiddling Hacks

Conditionally set or clear bits without branching
bool f; // conditional flag
unsigned int m; // the bit mask
unsigned int w; // the word to modify: if (f) w |= m; else w &= ~m;

w ^= (-f ^ w) & m;

// OR, for superscalar CPUs:
w = (w & ~m) | (-f & m);

image-20230813234458300

2023-09-25 Parsing integers quickly with AVX-512 – Daniel Lemire's blog

If I give a programmer a string such as "9223372036854775808" and I ask them to convert it to an integer, they might do the following in C++:

std::string s = ....
uint64_t val;
auto [ptr, ec] =
std::from_chars(s.data(), s.data() + s.size(), val);
if (ec != std::errc()) {} // I have an error !
// val holds the value

It is very fast: you can parse a sequence of random 32-bit integers at about 40 cycles per integer, using about 128 instructions.

Can you do better?

auto DIGIT_VALUE_BASE10_8BIT =
_mm256_set_epi8(1, 10, 1, 10, 1, 10, 1, 10,
1, 10, 1, 10, 1, 10, 1, 10,
1, 10, 1, 10, 1, 10, 1, 10,
1, 10, 1, 10, 1, 10, 1, 10);
auto DIGIT_VALUE_BASE10E2_8BIT = _mm_set_epi8(
1, 100, 1, 100, 1, 100, 1, 100, 1, 100, 1, 100, 1, 100, 1, 100);
auto DIGIT_VALUE_BASE10E4_16BIT =
_mm_set_epi16(1, 10000, 1, 10000, 1, 10000, 1, 10000);
auto base10e2_16bit =
_mm256_maddubs_epi16(base10_8bit, DIGIT_VALUE_BASE10_8BIT);
auto base10e2_8bit = _mm256_cvtepi16_epi8(base10e2_16bit);
auto base10e4_16bit =
_mm_maddubs_epi16(base10e2_8bit, DIGIT_VALUE_BASE10E2_8BIT);
auto base10e8_32bit =
_mm_madd_epi16(base10e4_16bit, DIGIT_VALUE_BASE10E4_16BIT);
AVX-5121.8 GB/s57 instructions/number17 cycles/number
std::from_chars0.8 GB/s128 instructions/number39 cycles/number

Compilers

2023-12-01 Compiler Options Hardening Guide for C and C++ | OpenSSF Best Practices Working Group

TL;DR: What compiler options should I use?

When compiling C or C++ code on compilers such as GCC and clang, turn on these flags for detecting vulnerabilities at compile time and enable run-time protection mechanisms:

-O2 -Wall -Wformat=2 -Wconversion -Wimplicit-fallthrough \
-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 \
-D_GLIBCXX_ASSERTIONS \
-fstrict-flex-arrays=3 \
-fstack-clash-protection -fstack-protector-strong \
-Wl,-z,nodlopen -Wl,-z,noexecstack \
-Wl,-z,relro -Wl,-z,now

Note that support for some options may differ between different compilers, e.g. support for -D_FORTIFY_SOURCE varies depending on the compiler2 and C standard library implementations. See the discussion below for background and for detailed discussion of each option.

When compiling code in any of the situations in the below table, add the corresponding additional options:

WhenAdditional options flags
using GCC-Wtrampolines
for executables-fPIE -pie
for shared libraries-fPIC -shared
for x86_64-fcf-protection=full
for aarch64-mbranch-protection=standard
for production code-fno-delete-null-pointer-checks -fno-strict-overflow -fno-strict-aliasing -ftrivial-auto-var-init=zero

C++ Build tools

  • 2022-10-03 Ninja

    Ninja is a small build system with a focus on speed

  • 2022-10-03 Cmake

    CMake is an open-source, cross-platform family of tools designed to build, test and package software. CMake is used to control the software compilation process using simple platform and compiler independent configuration files

C++ profiling tools

C++ and Unicode

It's _MSC_VER. More info at MSDN and at predef.

But, be aware that some other compilers may also define it, e.g. Intel's C++ Compiler for Windows also defines _MSC_VER. If this is a concern, use #if _MSC_VER && !__INTEL_COMPILER.
BOOL WINAPI SetConsoleCP(
_In_ UINT wCodePageID
);
#include <windows.h>
#include <iostream>

int main(){
SetConsoleOutputCP(CP_UTF8);
std::cout << "1) ✊\n";
std::cout << "2) ✋\n";
std::cout << "3) ✌️\n";
return 0;
}

2023-07-25 Unicode is harder than you think · mcilloni's blog

Reading the excellent article by JeanHeyd Meneide on how broken string encoding in C/C++ is made me realise that Unicode is a topic that is often overlooked by a large number of developers. In my experience, there’s a lot of confusion and wrong expectations on what Unicode is, and what best practices to follow when dealing with strings that may contain characters outside of the ASCII range.

This article attempts to briefly summarise and clarify some of the most common misconceptions I’ve seen people struggle with, and some of the pitfalls that tend to recur in codebases that have to deal with non-ASCII text.

CMAKE

C++ Libraries and Lib Collections

2023-09-02 Home | Csound Community

Csound is a sound and music computing system which was originally developed by Barry Vercoe in 1985 at MIT Media Lab. Since the 90s, it has been developed by a group of core developers. A wider community of volunteers contribute examples, documentation, articles, and takes part in the Csound development with bug reports, feature requests and discussions with the core development team.

2023-02-02 A list of open source C++ libraries - cppreference.com

The objective of this page is to build a comprehensive list of open source C++ libraries, so that when one needs an implementation of particular functionality, one needn't to waste time searching on web.

2023-05-10 DNedic/lockfree: A collection of lock-free data structures written in standard C++11

What are lock-free data structures? Lock-free data structures are data structures that are thread and interrupt safe without having to use mutual exclusion mechanisms. Lock-free data structures are most useful for inter process communication, but due to the efficiency of lockfree, it can safely be used for single threaded uses as well, making it good for general purpose use.

2023-07-23 STX: Main Page

lamarrr/STX: C++17 & C++ 20 error-handling and utility extensions. These monadic types not only make error handling easier but also make the paths more obvious to the compiler for optimizations. Monads can be simply thought of as abstract types of actions. Their monadic nature makes it easy to operate on them as pipelines and in the process eliminate redundant error-handling logic code.

  • stx::Result<T, E> : Type for relaying the result of a function that can fail or succeed (with monadic extensions)
  • stx::Option<T> : Type for safe optional values (with monadic extensions)

2023-09-15 hanickadot/compile-time-regular-expressions: Compile Time Regular Expression in C++

Fast compile-time regular expressions with support for matching/searching/capturing during compile-time or runtime.

You can use the single header version from directory single-header. This header can be regenerated with make single-header. If you are using cmake, you can add this directory as subdirectory and link to target ctre.

ctre::match<"REGEX">(subject); // C++20
"REGEX"_ctre.match(subject); // C++17 + N3599 extension
  • Matching
  • Searching (search or starts_with)
  • Capturing content (named captures are supported too)
  • Back-Reference (\g{N} syntax, and \1...\9 syntax too)
  • Multiline support (with multi_) functions
  • Unicode properties and UTF-8 support

C++ Machine Learning

2023-02-18 Introduction to Machine Learning using C++ Engineering Education EngEd Program Section

The article aims to teach beginners how to use C++ for machine learning by providing a clear and concise tutorial with code examples. It also encourages readers to explore more advanced topics and applications of machine learning using C++

2023-02-01 C++ Neural Network in a Weekend – Jeremy's Blog

Would you like to write a neural network from start to finish? Are you perhaps shaky on some of the fundamental concepts and derivations, such as categorical cross-entropy loss or backpropagation? Alternatively, would you like an introduction to machine learning without relying on “magical” frameworks that seem to perform AI miracles with only a few lines of code (and just as little intuition)? If so, this article was written for you.

2023-01-27 When Should You Learn Machine Learning using C++? by Ahmed Hashesh Embedded House Medium

This article is part of a series that address the implementation of Machine learning algorithms in C++, throughout this series, We will be implementing basic Machine learning algorithms using C++ features.

Video

Channels

Talks

2023-08-01 SIMD Libraries in C++ - Jeff Garland - CppNow 2023 - YouTube

image-20230801215244268

Application libraries:

Developer libraries

2023-03-25 CSE325 Lecture Videos - YouTube

Low-Level C Programming – CSE 325 Lecture Videos

2022-12-28 Concurrency Patterns - Rainer Grimm - CppCon 2021 - YouTube

This one is about the OOP C++ Concurrency patterns, like this one for locks:

image-20221228132809167

2022-11-03 Typical C++, But Why? - Björn Fahller - NDC TechTown 2022 - YouTube

some advice on writing more strongly-typed code, not only in C++

image-20221105170012423

2022-10-14 Dependency management in C++ - Xavier Bonaventura - code::dive 2019 - YouTube

======= C Programming Language ==========

Dev C Articles

  • 2022-03-05 Beginner's Guide to Linkers

    This article is intended to help C & C++ programmers understand the essentials of what the linker does. I've explained this to a number of colleagues over the years, so I decided it was time to write it down so that it's more widely available.

  • 2022-11-28 Everything I wish I knew when learning C - Tom M

    Learning C was quite difficult for me. The basics of the language itself weren’t so bad, but “programming in C” requires a lot of other kinds of knowledge which aren’t as easy to pick up on:

    • C has no environment which smooths out platform or OS differences; you need to know about your platform too
    • there are many C compiler options and build tools, making even running a simple program involve lots of decisions
    • there are important concepts related to CPUs, OSes, compiled code in general
    • it’s used in such varied ways that there’s far less a centralised “community” or style than other languages
  • 2022-11-13 Building a simple shell in C

    A basic shell that prints a prompt, waits for user to enter command and prints what they entered on the next line

  • 2022-11-13 Build Your Own Text Editor

    Welcome! This is an instruction booklet that shows you how to build a text editor in C.

    The text editor is antirez’s kilo, with some changes. It’s about 1000 lines of C in a single file with no dependencies, and it implements all the basic features you expect in a minimal editor, as well as syntax highlighting and a search feature.

  • 2023-05-22 Memory Allocation

One thing that all programs on your computer have in common is a need for memory. Programs need to be loaded from your hard drive into memory before they can be run. While running, the majority of what programs do is load values from memory, do some computation on them, and then store the result back in memory.

In this post I'm going to introduce you to the basics of memory allocation. Allocators exist because it's not enough to have memory available, you need to use it effectively. We will visually explore how simple allocators work. We'll see some of the problems that they try to solve, and some of the techniques used to solve them. At the end of this post, you should know everything you need to know to write your own allocator.

image-20230528170203659

There are some tricks, quirks and features (some quite fundamental to the language!) which seems to throw even experienced developers off the track. Thus I did a sloppy job of gathering some of them in this post (in no particular order) with even sloppier short explanations and/or examples (or quote of thereof).

2023-06-30 Structures in C: From Basics to Memory Alignment – Abstract Expression

Structures allow us to combine several variables to create a new data type. Some other languages support the same concept but call it “records”. If you come from object-oriented programming you can think about them as classes without methods.

image-20230702152138229

Books

1993 ⭐ Object-oriented Programming with ANSI-C (1993) [pdf]

Retro document! but very well written

image-20230629003429585

RSS

Dev C Tools

Dev C Libs

Net

2023-05-17 Home - DPDK

2023-05-17 DPDK/dpdk: Data Plane Development Kit

DPDK (Data Plane Development Kit) is an open-source software project that provides a set of libraries and drivers for fast packet processing in user space. Its main goal is to increase the performance of packet processing applications running on standard computing platforms. The project is hosted and can be accessed at www.dpdk.org. It's widely used in network interface cards, routers, firewalls, and other networking appliances.

C language development

  • 2022-03-05 Cello • High Level C

    Cello is a library that brings higher level programming to C. New C syntax for New Era!

#include "Cello.h"

int main(int argc, char** argv) {

/* Stack objects are created using "$" */
var i0 = $(Int, 5);
var i1 = $(Int, 3);
var i2 = $(Int, 4);

/* Heap objects are created using "new" */
var items = new(Array, Int, i0, i1, i2);

/* Collections can be looped over */
foreach (item in items) {
print("Object %$ is of type %$\n",
item, type_of(item));
}

/* Heap objects destructed via Garbage Collection */
return 0;
}
  • 2022-03-16 libmill Libmill is a library that introduces Go-style concurrency to C
go(foo(arg1, arg2, arg3));
chan ch = chmake(int, 0);
chan ch = chmake(int, 1000);
chs(ch, int, 42);

SIMD

A computer science professor at the University of Quebec (TELUQ). View all posts by Daniel Lemire

SIMD stands for "Single Instruction Multiple Data," and is one of several approaches to parallelism found in modern high-performance computing.

Vector instructions are a primary example of SIMD parallelism in modern CPUs. For instance, the vector add instruction is a single instruction (add) that acts on multiple data (vectors) to yield a vector of sums. Given the two vectors (1, 2, 3, 4) and (5, 6, 7, 8), the vector result (6, 8, 10, 12) is produced in a single operation. This operation is illustrated in the diagram and linked video below.

image-20230608160855199

2023-07-02 Parsing time stamps faster with SIMD instructions – Daniel Lemire's blog

Standard:

#include <time.h>
#include <stdio.h>
int main() {
char buffer[15];
struct tm timeinfo;
time_t rawtime;
time(&rawtime);
gmtime_r(&rawtime, &timeinfo);
size_t len = strftime(buffer, 15, "%Y%m%d%H%M%S", &timeinfo);
buffer[14] = '\0';
puts(buffer);
}

SIMD:

 __m128i v = _mm_loadu_si128((const __m128i *)date_string);
v = _mm_sub_epi8(v, _mm_set1_epi8(0x30));
__m128i limit =
_mm_setr_epi8(9, 9, 9, 9, 1, 9, 3, 9, 2, 9, 5, 9, 5, 9, -1, -1);
__m128i abide_by_limits = _mm_subs_epu8(v, limit); // must be all zero
const __m128i weights = _mm_setr_epi8(
10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 0, 0);
v = _mm_maddubs_epi16(v, weights);
__m128i limit16 =
_mm_setr_epi16(99,99, 12, 31, 23, 59, 59, -1);
__m128i abide_by_limits16 = _mm_subs_epu16(v, limit16);
__m128i limits = _mm_or_si128(abide_by_limits16,abide_by_limits);
if (!_mm_test_all_zeros(limits, limits)) {
return false;
}
instructions per stamptime per stamp
standard C with strptime70046
SIMD approach657.9