C, CPP & CMake - feliyur/exercises GitHub Wiki

Static vs. Dynamic Linking on Linux

https://opensource.com/article/20/6/linux-libraries#:~:text=so%20

https://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html

Building Boost

January 2023, boost 1.81.0

Now that VS 2022 is released and the version of Boost is boost_1_79_0 the process is simple.

  1. Download the windows boost libraries from https://www.boost.org/users/history/version_1_79_0.html
  2. Unzip to a path of your choice for eg E:\boost_1_79_0
  3. Open Developer Command Prompt For VS 2022 and cd into extracted boost directory
  4. Issue the command bootstrap vc143 hit Enter and wait
  5. Next issue the command .\b2 hit Enter and grab tea or coffee. On successful completion the above procedure will build boost static libraries found in eg E:\boost_1_79_0\stage\lib

Taken from here.

Description page created in December 2018, using boost 1.64.0 (version from 2017. Current version: 1.69.0), mingw-w64 7.1 and VS 2017 on Windows 10, gcc 5.4.0 on Ubuntu 16.04.

Boost is a set of C++ libraries extending the C++ standard library with additional cross-platform functionality. Boost is required in building from source of many established libraries. To link against boost, typically one needs to provide:

  1. include directory, dependent on boost version, typically in boost_version_root/boost
  2. lib directory, typically boost_version_root/stage/lib. Must match the include's version, as well as be compatible with current compiler.
    • As usual, linking can be static or dynamic (shared library). In the latter case, dll/so files must be copied with the resultant binary or be found on system path. On windows, .lib files are also found in stage/lib.

CMake has a built-in FindBoost script (invoked by find_package(boost ...)).

Download Boost

To download prebuilt binaries, search for "boost prebuilt" + your platform and compiler. On Unix, often comes bundled in system, or can install though package manager (brew, apt-get, etc). boost-python (or boost-python3) package needs to be installed separately.

To download sources for build:

Building Boost

Generally, building takes the following commands:

cd ${BOOST_ROOT_DIRECTORY}
./bootstrap.{bat, sh}   # sets up the boost build engine (see platform-specific description below for details)
./b2 ${BUILD_OPTIONS} stage # runs boost build, copies results into stage directory

Boost binaries are built in boost_version_root/bin.v2 (can reuse for subsequent builds), then copied into stage directory.

Typical (recommended) parameters for b2: ./b2 --address-model=64 --build-type=complete (build 64 bit binaries, 4 versions of each - equivalent of {link=static/shared} x {runtime-link=static/shared}). Here and here is an explanation of those and additional options.

Additional parameters can be configured in project-config.jam or user-config.jam.

Unix

Invoke bootstrap.sh. To use --build-type=complete, need to specify --layout=versioned to b2. Make sure to edit project-config.jam (after bootstrap but before b2) to use desired version of python, editing python configuration, around line 21, like so (mind the spaces, semicolon!):

    using python : 3.6 : /usr/bin/python3.6 ;

Edit: Need to also specify -fPIC (position independent code) to be able to link to load from python later. Explained here. Edit line 12 to include this compilation flag (again, mind all spaces and trailing semicolon):

    using gcc : : : <cxxflags>-fPIC ; 

For completeness, run the commands:

./bootstrap.sh
./b2 --address-model=64 --layout=versioned --build-type=complete stage

Windows

Visual Studio

  1. Run your VS "native tools" prompt as administrator. Use it for the build

    • Win+s ==> type "native tools" ==> choose VS version and target (x64 for 64 bit) ==> right click ==> Run as Administrator
    • Equivalently, can call vcvars64.bat (or vcvars32.bat) in a regular cmd (still, Run as Administrator).
      • example location: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\
  2. Edit your project-config.jam (after running bootstrap) to choose msvc and python version/location according to the below example

    • Note that visual studio release years do not correspond to version numbers. To find out your VS version number, see the Native Tools prompt welcome message, or the VS wikipedia page
project-config.jam:
import option ; 
 
using msvc : 15.0 : "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\VC\\Tools\\MSVC\\14.10.25017\\bin\\HostX64\\x64\\cl.exe" ;

# ---------------------
# Python configuration.
# ---------------------

# Configure specific Python version.
# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ;

using python 
    : 3.6                   # Version
    : C:\\Python\\Python36\\python.exe      # Python Path
    : C:\\Python\\Python36\\include         # include path
    : C:\\Python\\Python36\\libs            # lib path(s)
    : <define>BOOST_ALL_NO_LIB=1
    ;
	
option.set keep-going : false ; 
 

mingw-w64

One reason not to use the microsoft compiler on Windows for cross-platform projects, is that JetBrains CLion (as of version 2018.3.1) does not support debugging with visual studio (does support build). Instead, can use either cygwin or mingw-w64 (see wikipedia for relation to mingw). Specifics for this compiler are:

./bootstrap.bat gcc
./b2 ${OTHER_OPTIONS} define=MS_WIN64 cxxflags="-D_hypot=hypot"

The former define=MS_WIN64 is (currently) always required (see here), whereas cxxflags="-D_hypot=hypot" is only required if building with boost.python (see here).

Note that build of some packages fails (as of mingw-w64 7.1, boost 1.64.0) because of relatively old gcc version.

project-config.jam
import option ; 
 
using gcc : 7.1 : C:\\mingw-w64\\x86_64-7.1.0-posix-seh-rt_v5-rev0\\mingw64\\bin\\g++.exe
;

# ---------------------
# Python configuration.
# ---------------------

# Configure specific Python version.
# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ;

using python 
    : 3.6                   # Version
    : C:\\Python\\Python36\\python.exe      # Python Path
    : C:\\Python\\Python36\\include         # include path
    : C:\\Python\\Python36\\libs            # lib path(s)
    ;
	
option.set keep-going : false ; 

Ramping up on modern C++

To ramp up on modern C++, here’s a list of key topics in order of decreasing importance:

1. Smart Pointers

  • Unique Pointer (std::unique_ptr): Ownership model, RAII (Resource Acquisition Is Initialization).
  • Shared Pointer (std::shared_ptr): Reference counting, cyclic dependencies.
  • Weak Pointer (std::weak_ptr): Breaking cyclic dependencies, observing shared resources.

2. Move Semantics and Rvalue References

  • Move Constructors and Move Assignment Operators: Efficient resource transfer.
  • Rvalue References (&&): Understanding the difference between lvalues and rvalues.
  • Perfect Forwarding: Using std::forward and universal references.

3. Lambda Expressions

  • Syntax: Captures, parameters, and return types.
  • Usage: Inline function objects, capturing by value or reference, mutable lambdas.

4. Standard Library Containers and Algorithms

  • Containers: Enhancements in containers like std::vector, std::unordered_map, std::array, std::tuple, and more.
  • Algorithms: Using modern algorithms like std::for_each, std::find, std::transform, std::copy_if, etc.
  • Iterators: Enhanced iterator functionality, including std::reverse_iterator, std::move_iterator.

5. Concurrency

  • Threading (std::thread): Basic threading, thread joining, detaching.
  • Mutexes and Locks (std::mutex, std::lock_guard): Synchronization primitives, avoiding deadlock.
  • Condition Variables (std::condition_variable): Synchronization between threads.
  • Futures and Promises (std::future, std::promise): Asynchronous operations.
  • Atomic Operations (std::atomic): Atomicity, lock-free programming.

6. Range-based for Loops

  • Simplified looping over containers and arrays.

7. Auto Keyword

  • Type inference, reduced verbosity, and improved code maintainability.

8. Initialization Enhancements

  • Uniform Initialization: Brace-enclosed initializer lists.
  • Default and Delete Functions: Control over compiler-generated functions.
  • Constructor Delegation: Reuse of constructors within a class.

9. Type Traits and std::type_traits

  • Compile-time type information, SFINAE (Substitution Failure Is Not An Error).

10. constexpr and consteval

  • constexpr: Compile-time constant expressions, functions, and variables.
  • consteval: Ensuring expressions are evaluated at compile time.

11. Templates and Template Metaprogramming

  • Variadic Templates: Handling variable numbers of template arguments.
  • Template Aliases (using): Simplified template syntax.
  • Template Specialization: Partial and explicit specialization.
  • Concepts (C++20): Constraints on template parameters for more readable error messages.

12. Modern C++ Syntax and Language Features

  • nullptr: Null pointer constant.
  • Scoped Enums (enum class): Type-safe enums.
  • Delegating Constructors: Streamlining constructor definitions.
  • Inline Namespaces: Controlling namespace versioning.

13. Error Handling with Exceptions

  • std::exception_ptr: Propagating exceptions across threads.
  • std::optional and std::variant: Alternatives to error handling.

14. Filesystem Library (C++17)

  • Managing files and directories in a platform-independent way using std::filesystem.

15. Coroutines (C++20)

  • co_await, co_yield, co_return: Asynchronous and lazy evaluation using coroutines.

16. Modules (C++20)

  • Modularization: Replacing header files with modules for better encapsulation and faster compilation.

17. Ranges (C++20)

  • std::ranges: Simplified manipulation of collections, replacing conventional iterator-based approaches.

18. Networking Library (C++20)

  • Networking TS: Basic networking primitives for TCP/IP programming.

19. Reflection (Future Standard, Experimental in C++20/23)

  • Compile-time Reflection: Introspection capabilities for types and structures.

20. Design Patterns and Idioms in Modern C++

  • Rule of Five: Ensuring proper resource management.
  • RAII (Resource Acquisition Is Initialization): Automatic resource management using constructors and destructors.
  • Copy-and-Swap Idiom: Exception-safe copy and assignment.
  • CRTP (Curiously Recurring Template Pattern): Metaprogramming technique.

Conclusion:

Start with Smart Pointers and Move Semantics, then progress through Lambda Expressions, Concurrency, and the auto keyword, as these are foundational for modern C++. As you become more comfortable, explore concurrency, modern syntax, and the various new libraries introduced in C++11 and beyond.

⚠️ **GitHub.com Fallback** ⚠️