- GitHub - AnthonyCalandra/modern-cpp-features: A cheatsheet of modern C++ language and library features.
- C++ Cheat Sheets & Infographics | hacking C++
- linux/tools/include/nolibc at master · torvalds/linux · GitHub
- https://vorpus.org/blog/why-does-calloc-exist/
gdb /bin/true -ex 'b main' -ex 'r'
printf 'int main(){}' | gcc -o /tmp/1 -x c - && gdb /tmp/1 -ex 'b main' -ex 'r'# Optional: Outputs `configure`
autoreconf -fi
./configure
make
sudo make install
# ||
./configure --prefix="$HOME/foo"
# ||
make prefix="$HOME/foo" installPKG_CONFIG_PATHset to path containing .pc files
gcc -fPIE -pie
# vs.
gcc -no-pie -fno-pic- https://unix.stackexchange.com/questions/89211/how-to-test-whether-a-linux-binary-was-compiled-as-position-independent-code
- https://codywu2010.wordpress.com/2014/11/29/about-elf-pie-pic-and-else/
- IA-32, a variant of x86, commonly known as i386 (the name used by Debian) or i686 (which, like IA-32, are generations of the x86 architecture series)
- x86-64, also known as x64 or amd64 (the name used by Debian) (not to be confused with IA-64 which is completely different)
od -An -t x1 -j 4 -N 1 foo
# Output: 01 if 32bit, 02 if 64bitReferences:
- https://code.woboq.org/userspace/glibc/sysdeps/unix/sysv/linux/x86/time.c.html
- if vDSO available:
_dl_vdso_vsym ("__vdso_time", &linux26) ?: &__time_syscall
- else fallback on syscall:
static time_t __time_syscall (time_t *t) { INTERNAL_SYSCALL_DECL (err); return INTERNAL_SYSCALL (time, err, 1, t); }
- if vDSO available:
- https://code.woboq.org/userspace/glibc/sysdeps/unix/sysv/linux/x86_64/sysdep.h.html#234
- redirect to syscall macro (e.g. nr=1 if arg1 passed)
#define INTERNAL_SYSCALL(name, err, nr, args...) \ internal_syscall##nr (SYS_ify (name), err, args)
- redirect to syscall macro (e.g. nr=1 if arg1 passed)
- https://code.woboq.org/userspace/glibc/sysdeps/unix/sysv/linux/x86_64/sysdep.h.html
- convert syscall name to nr
/* For Linux we can use the system call table in the header file /usr/include/asm/unistd.h of the kernel. But these symbols do not follow the SYS_* syntax so we have to redefine the `SYS_ify' macro here. */ #undef SYS_ify #define SYS_ify(syscall_name) __NR_##syscall_name
- check which table to lookup based on arch
# ifdef __i386__ # include <asm/unistd_32.h> # elif defined(__ILP32__) # include <asm/unistd_x32.h> # else # include <asm/unistd_64.h> # endif
- lookup syscall nr in table
#define __NR_time 201
- convert syscall name to nr
# GCC / Clang
c++filt
# MSVC
undname '?func1@a@@AAEXH@Z'
# Watcom
# https://github.com/open-watcom/open-watcom-v2/blob/master/bld/lib_misc/c/demangle.c
demangle 'W?h$n(i)v'strip - removes symbol names
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
# || From build commands
# References: https://github.com/rizsotto/Bear
bear make
# vscode
bear -a -o .vscode/compile_commands.json make
# c_cpp_properties.json
# "compileCommands": "${workspaceFolder}/.vscode/compile_commands.json"
# Validation
test -f compile_commands.jsonprintf '#include<stdio.h>
int main() { puts("Hi!"); return 0; }' \
| i686-linux-musl-gcc -xc - \
&& ./a.out; rm -f a.out# create shared library
gcc foo.c -o foo -shared -fPIC
# validate paths
ld "-L$HOME/opt/libunwind/src/.libs" -lunwind --verbose 2>&1 | grep succeeded
# linking shared library
gcc -L. -lfoo foo.c -o foo
LD_RUNTIME_PATH=. ./foo
# ||
gcc -L. -lfoo -Wl,-rpath,$PWD foo.c -o foo
./foo
# override dynamic linking behaviour, e.g. link libfirst.a and libsecond.so:
gcc -Wl,-Bstatic -lfirst -Wl,-Bdynamic -lsecond
# override system shared libraries
./configure LDFLAGS="-Wl,-rpath,$HOME/opt/libunwind/src/.libs -L$HOME/opt/libunwind/src/.libs"
# both c and c++
./configure \
LDFLAGS="-L/foo/usr/lib" \
CPPFLAGS="-I/foo" \
CPATH="/foo"
# only c
./configure \
CFLAGS="-I/foo" \
C_INCLUDE_PATH="/foo"
# only c++
./configure \
CXXFLAGS="-I/foo" \
CPLUS_INCLUDE_PATH="/foo"
# include library `libfoo.so.*`
LIBS=-lfoo ./configure
# include specific library version
LIBS=-l:libfoo.so.123 ./configure
# debug
less ./config.log
# workaround for "/usr/include/linux/errno.h:1:10: fatal error: 'asm/errno.h' file not found"
ln -s /usr/include/asm-generic /usr/include/asm- https://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html
- https://gcc.gnu.org/onlinedocs/cpp/Environment-Variables.html
reimp.exe -d foo.lib
dlltool.exe -k -d foo.def -l foo.a- https://trinitycore.atlassian.net/wiki/spaces/tc/pages/2130053/MinGW+GCC+toolchain+Win
- https://wiki.tcl-lang.org/page/How+to+create+mingw32+libraries+from+DLLs
- https://stackoverflow.com/questions/2472924/linking-to-msvc-dll-from-mingw
On /include/foo.h:
#include "foo.h"
#include "bar.h"CPPFLAGS="-I/include"
https://stackoverflow.com/questions/10613126/what-are-the-differences-between-std-c11-and-std-gnu11
# With configure
./configure LDFLAGS=-static
env CXXFLAGS=-static --enable-static --disable-shared -fPIC --prefix="$(pwd)" make
# With pkg_config
LDFLAGS="-static" PKG_CONFIG="pkg-config --static" ./configure --disable-shared --enable-static
make -j4 V=1 LDFLAGS="-static -all-static"
# With configure (cross-compile)
CC=$HOME/share/toolchains/aarch64-linux-musl-cross/bin/aarch64-linux-musl-gcc ./configure --host=aarch64-linux-musl LDFLAGS=-static
# With Makefile (cross-compile)
make CC=./mips64-linux-musl-cross/bin/mips64-linux-musl-gcc LDFLAGS=-static
./mips64-linux-musl-cross/bin/mips64-linux-musl-gcc -O -Wall -std=c90 -c hello.c
./mips64-linux-musl-cross/bin/mips64-linux-musl-gcc -static -o hello hello.o
# With QEMU (cross-compile)
docker run --platform linux/arm64 -it -v "$HOME/share:/share:z" arm64v8/alpine:3.22.0- musl
- stdenv, REALGCC
docker run -it -v "$HOME/share:/share:z" alpine:3.22.0 # From package sources # References: # - https://unix.stackexchange.com/questions/496755/how-to-get-the-source-code-used-to-build-the-packages-of-the-base-alpine-linux-d # - https://wiki.alpinelinux.org/wiki/Creating_an_Alpine_package # - https://wiki.alpinelinux.org/wiki/APKBUILD_Reference # - https://moebuta.org/posts/compiling-static-binaries-with-alpine/ apk update apk add --no-cache alpine-sdk autoconf automake binutils binutils-dev byacc elfutils-dev flex gawk gcc gettext gettext-dev libtool libnl3-dev linux-headers musl-dev sudo cd /opt git clone --depth 1 --branch v3.22.0 git://git.alpinelinux.org/aports # Build app= cd /opt/aports/main/"$app" # Override pkg-config dependencies (e.g. when specifying static libs) # References: [Static compilation errors \- tmux 2\.9, ncurses 6\.1, libevent 2\.1\.8 · Issue \#1729 · tmux/tmux · GitHub](https://github.com/tmux/tmux/issues/1729) # export PKG_CONFIG=/bin/true export PKG_CONFIG='pkg-config --static' # [Edit APKBUILD to include `-static` in CFLAGS / `LDFLAGS="-static" ./configure` / `make LDFLAGS="-static -all-static"`] # [For curl: https://github.com/moparisthebest/static-curl/blob/master/build.sh] # [For strace: ~/share/alpine/static/strace613.sh] echo | abuild-keygen -a -i abuild -Fcr # Unpack tar -xzvf /root/packages/main/x86_64/"$app".apk cp "$app" /share/ # || cp ./pkg/strace/usr/bin/"$app" /share/ strip /share/"$app"
- Unsupported in
libtool
-
clang-tidy
-
ASAN
- gcc -fuse-ld=gold
- gcc -g -fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -static-libasan
-
valgrind --vgdb=full --vgdb-error=0 ./a.out
-
cpplint
-
clazy
-
include-what-you-use -Xiwyu
-
gcov
-
gcc -ggdb3
-
gdb, cgdb
-D_FORTIFY_SOURCE=1 python gdb.execute() python gdb.parser_and_eval() python help('gdb') -
lldb
-
rr
-
undodb
-
live recorder
-
perf, sysprof, gperftools (pprof)
-
valgrind --trace-children=yes
-
ftrace: trace-cmd
-
strace -k
-
GitHub - dalance/flexlint: A flexible linter with rules defined by regular expression
-
Finding Number Related Memory Corruption Vulns
-ftrapv -fsanitize=integer,float-cast-overflow -
https://chromium.googlesource.com/chromium/src.git/+/master/docs/linux/eclipse_dev.md
uses ptrace
info signals when to stop, print, pass to inferior handle SIGINT stop print nopass
thread apply all backtrace full
gdbserver localhost:2000 ./a.out target remote localhost:2000
b main
b _exit
command 1
record
command 2
run
reverse-stepi
rr replay
watch foo stop when foo is modified watch -l foo watch location rwatch foo stop when foo is read watch foo thread 3 stop when thread 3 modifies foo watch foo if foo > 10 stop when foo is> 1O
Use dprintf to put printf's in your code without recompiling. e.g. dprintf mutex_lock,"m is %p m->magic is %u\n",m,m->magic
Control how the printfs happen:
set dprintf-style gdb|call|agent set dprintf-function fprintf set dprintf-channel mylog
print *((int*(*)())__errno_location)()Cachegrind: cache profiler. simulates l1, D1, L2 caches Callgrind: like cachegrind, but also with call-graphs Massif: heap profiler Helgrind: find race conditions in multithreaded programs DRD: Data Race Detector. Like Helgrind, but uses less memory. Lackey / None: demo/unit test of valgrind itself.
-fsanitize=address
https://devblogs.microsoft.com/cppblog/finding-bugs-with-addresssanitizer-msvc-compiler/
foo(const map<string, string>& bar)
map::at()-fsanitize-address-use-after-scope
std::atomics, mutexsetbuf(stdout, NULL);shared_ptr<T>
ok: reference count, control block
ko: T
ko: shared_ptr pointers
atomic<shared_ptr>// RAII types + default constructor
std::string(foo);
// -Wshadow
// good but ko: -Wshadow-compatible-local
unique_lock<mutex> g(m_mutex);// Second argument is a pointer to the type of std::fclose, we could also have
// written it out explicitly as std::unique_ptr<FILE, int (*)(FILE*)>.
using FilePtr = std::unique_ptr<FILE, decltype(std::fclose) *>;
// Instantiate the FILE* with the destructor we want.
FilePtr file(std::fopen(filename, "rbe"), std::fclose);
// Do stuff with the file
std::fread(buf_.data(), 1, buf_.size(), file.get());int i = 0;
auto p = &i; // int*
auto* p = &i; // still int*In C, &x types at T* for some T, where T is the decayed type of the lvalue x. therefore, T = int, so T* = int*. therefore p must have type int*. The type inference "flows" from the value on the right to the type. If auto is there alone, everything is inferred. If you add a , it ensures the value is a pointer to an inferred type. & creates a pointer, auto constrains the possible values. changes auto to infer the rest of type of the value on the right side of assignment after it's established that the value is a pointer. The same way * in
int* a = b;requires b to be a pointer and requires it to be a pointer to int. auto is not a type, it's a constraint. let p : Pointer = &i // int* let p : Pointer = &i // auto* let p = &i // auto
// struct.pack('>f', 225.22).hex()
int i = 0x43613852;
float f = *((float*)&i);
printf("225.22 = %.2f\n", f);https://vcpkg.readthedocs.io/en/latest/
conan info .. conan search gtest -r conan-center
Decentralized servers
- OSS, corporate, private, etc Central cache on local PC
- sharing of the dependencies data among different projects Support for
- sources only (do not use prebuilt binaries even if available)
- sources + prebuilt binaries (improves build performance)
- binaries only (for closed source projects and development tools) Offline use
heavy hitters, majority element, boyer-moore's majority vote elements that occur at least x% of the time e.g. throttle users with multiple requests
morris traversal O(1) space tree traversal e.g. free children without recursion
reservoir sampling given a stream of data, select k items at random e.g. biggrep
HyperLogLog count number of distinct elements by leading zeros, partition input space, apply harmonic mean
#include <algorithm>
adjacent_find partitions partial_sort ~= nth_element + sort rotate gather = 2 stable_partition, pair inserted in point set_difference
preserve prior ordering whenever there is a conflict e.g. priority queue for same values
https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms
sudo dnf install -y boost-build boost-devel boost-jam boost-python3-devel python3-devel sudo ln -fs /usr/bin/bjam /usr/bin/b2 sudo ln -fs /usr/lib64/libpython3.7m.so /usr/lib64/libpython3.7.so source ~/code/sand/boost-build/profile.sh
#define protected public
#define private public
#define final
#include <foo.h>assert state has not changed between function calls
# crosscompiling from linux to 32-bit exe
i686-w64-mingw32-gcc foo.c -lws2_32 -o foo.exe
# crosscompiling from linux to 64-bit exe
x86_64-w64-mingw32-gcc foo.c -lws2_32 -o foo.exehttps://virtuallyfun.com/wordpress/2020/02/01/cross-compiling-sdl-1-2-15-for-arm-win32/
C:\proj\ss\SDL-1.2.15\VisualC\SDL>link /dll -out:sdl.dll *.obj winmm.lib dxguid.lib gdi32.lib user32.lib advapi32.lib dxguid.lib uuid.lib dxguid.lib Version.res
Microsoft (R) Incremental Linker Version 14.24.28315.0
Copyright (C) Microsoft Corporation. All rights reserved.
Creating library sdl.lib and object sdl.exp
SDL_dx5events.obj : error LNK2001: unresolved external symbol GUID_SysMouse
strings ~/Downloads/dxguid.lib | grep GUID_SysMouse
# Output:
# _GUID_SysMouseDEFINE_GUID(GUID_SysMouse, 0x6F1D2B60,0xD5A0,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00);https://github.com/tpn/winsdk-10/blob/master/Include/10.0.10240.0/shared/guiddef.h#L59
#ifndef DECLSPEC_SELECTANY
#if (_MSC_VER >= 1100)
#define DECLSPEC_SELECTANY __declspec(selectany)
#else
#define DECLSPEC_SELECTANY
#endif
#endif
// ...
#ifdef INITGUID
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
EXTERN_C const GUID DECLSPEC_SELECTANY name \
= { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
#else
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
EXTERN_C const GUID FAR name
#endif // INITGUIDhttps://docs.microsoft.com/en-us/cpp/cpp/declspec?view=vs-2019 https://stackoverflow.com/questions/2284610/what-is-declspec-and-when-do-i-need-to-use-it
=> define INITGUID
IOCCC's Best Abuse of the Rules in 1988
c #include "/dev/tty"
> it waits for you to type c code at your terminal, then compiles that. /dev/tty is the device representing the current terminal and can be read or written like a regular file
- https://twitter.com/eevee/status/678720136061169664
Undefined reference `__powf_finite` with clang 9.0.1, Linux 5.5.4-arch1-1 and glibc 2.31-1 · Issue #2146 · google/filament · GitHub c - What exactly is -fno-builtin doing here? - Stack Overflow Audacity – New Major Release – Compile Fix, for Portaudio.. – Adventures With Linux ™
mutex.lock();
// ...
if (foo) {
return; // missed unlock call
}
// ...
mutex.unlock();- Validation
gcc foo.c -fdump-tree-all -O3- /usr/include/limits.h
- Integer overflow as a result of adding two int type variables
int add(int a, int b) { if (a > 0 && b > 0) { // if (a + b < 0) { // can be optimized out if (a >= 0 ? b > INT_MAX - a : b < INT_MIN - a) { printf("%s\n", "overflow"); return 0; } } return a + b; }
- Product overflow check:
n * m * sizeof(int) < PTRDIFF_MAX- https://godbolt.org/z/PuCbFz
PTRDIFF_MAX / sizeof(int) / n >= m
- https://godbolt.org/z/QXPYsp
#include <stdint.h> #include <stdlib.h> _Bool f(size_t m, size_t n) { return n <= SIZE_MAX / (2 * sizeof(int)) && m <= SIZE_MAX / (2 * sizeof(int) * n); }
- https://godbolt.org/z/PuCbFz
- Prefer SecureZeroMemory, explicit_bzero over memset
- AppSec EU 2017 Dangerous Optimizations And The Loss Of Causality by Robert C Seacord - YouTube
- Schrödinger's Code - ACM Queue
- Quirks of C · GitHub
connect(manager, SIGNAL(finished(QNetworkReply*)), this,
SLOT(replyFinished(QNetworkReply*)));
void NetworkHandler::replyFinished(QNetworkReply *reply) {
qDebug() << reply->readAll();
}
void debugRequest(QNetworkRequest request, QByteArray data = QByteArray()) {
qDebug() << request.url().toString();
const QList<QByteArray>& rawHeaderList(request.rawHeaderList());
foreach (QByteArray rawHeader, rawHeaderList) {
qDebug() << request.rawHeader(rawHeader);
}
qDebug() << data;
}ldd /bin/true
LD_TRACE_LOADED_OBJECTS=1 /lib/ld-linux-x86-64.so.2 /bin/true
# https://github.com/ncopa/lddtree
objdump -x /bin/true | grep NEEDED
readelf -d /bin/true | grep NEEDEDgcc -dumpmachine- generating .clang-format file: pick config permutation with least changes