cpp compilation flags - pisanorg/w GitHub Wiki

Compiling programs

The simplest version is

g++ main.cpp

Assuming all the code is in main.cpp. This will produce an executable named a.out. We often want a more meaningfull name, so we can use:

g++ main.cpp -o factorial

Now, our executable is named factorial and we can execute it using ./factorial (assuming you are on a unix based system)

There are other flags that are useful in identifying bugs, so I often compile my programs as

g++ -std=c++11 -g -Wall -Wextra -Wno-sign-compare -fstack-protector-all -fsanitize=address main.cpp -o factorial

Of course, typing this in every time would slow things down and lead to errors, but luckily any modern IDE can be configured to use your desired compilation flags.

A sample CMakeLists.txt file, as used used by CLion, with explanations of all the flags is below. You can also use CMakeLists.txt files under unix by using cmake CMakeLists.txt which will generate a default Makefile that can be used with make to compile your program.

project(sample)

# Use a modern c++ version
# -std=c++11 OR -std=c++14 OR -std=c++17 OR -std=c++20

# Produce debugging information
# -g

# enables all the warnings
# -Wall

# enables some extra warning flags that are not enabled by -Wall
# -Wextra

# -Wno-sign-compare
# DO NOT warn when a comparison between signed and unsigned values
# we often use 'int' rather than 'unsigned int' for size of vector, string etc

# check for buffer overflows
# -fstack-protector-all

# detect out-of-bounds and use-after-free bugs
# -fsanitize=address

set(CMAKE_CXX_FLAGS "-std=c++11 -g -Wall -Wextra -Wno-sign-compare -fstack-protector-all -fsanitize=address")

add_executable(sample main.cpp)