Use CMake to build and run cross-platform (WIN32 and LINUX) code. (Part 1)

CMake is a build configuration tool. In other words, CMake generates Makefiles. This post gives an example on how to configure CMake (the actual content of CMakeLists.txt) to build and run C++ code in Windows as well as in Linux. Here it goes:

cmake_minimum_required(VERSION 3.22.1)

# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)
  cmake_policy(SET CMP0141 NEW)
  set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")

message(STATUS "Checking target system...")

   message(STATUS "Target system is Windows")
   set(BOOST_ROOT <Path to your boost directory in Windows>)
   set(Boost_INCLUDE_DIR ${BOOST_DIR})

   message(STATUS "Target system is Linux")
   set(BOOST_ROOT <Path to your boost directory in Linux>)

find_package(Boost REQUIRED)

project(<Project name>)
add_executable(<Project name>
target_compile_features(<Project name>PUBLIC cxx_std_20)
target_link_libraries(<Project name> ${Boost_SYSTEM_LIBRARY})

The example above links only the headers and not the binaries. How to link binaries will come in the next part.

Singleton Design Pattern

Imagine one fine Monday morning your project manager comes up to you and informs you that a new requirement has come up in your latest project. The Preference module in your software reads hard coded value but your project manager wants you to modify it so that the values are read from a database.

At once you start to think of how will you solve the problem. Here is a very simplified class diagram of Preferences class with its two callers:

Class diagram: Preferences is called multiple times by RpcCaller and ApiCaller.

Preference class has the values hard coded in there. RpcCaller and ApiCaller creates Preference objects each time they need to make a RPC call or an API call respectively. The Preference objects were quite light weighted so there were not a significant performance issue but now with the new requirement, creating so many objects will degrade the performance significantly.

So what will you do? Can you think of a solution?

I will highly recommend to pause for a minute and think of the what solution will you come up with.

Now lets look at different ways we could solve the problem. Clearly the requirement is:

  1. To create one and only one object of Preference class no matter what.
  2. Multiple classes require the same object instance.

There are two ways you can do it:

  1. Global variables.
    • But the problem with global variables is that it won’t restrict other classes to create another object.
    • So our requirement of one and only one could not be enforced using global variables.
  2. Singleton class.
    • A singleton class is one that has one object throughout the lifetime of the application.
    • It fits perfectly with our use case, so let’s explore what are singleton classes.

Singleton design pattern

The intent of this design pattern is to create a class which has one instance and provide a single point of access to that instance.

When should we use this design pattern?

  1. When only one instance of the class is required.
  2. There could only be one access point.
  3. and we need to manage the object instances.

So far so good but how does a singleton class should look like. I will be using C++ to demonstrate a very basic skeleton.

class Singleton
        static Singleton& GetInstance() {
            // Guaranteed to be destroyed and Instantiated on first use.
            static Singleton instance;
            return instance;
        // Private Constructor.
        Singleton() {}                   

        // Don't allow assignment.
        Singleton(Singleton const&) = delete;
        void operator=(Singleton const&) = delete;

Let me explain what is going on.

First, we make the constructor private and disallow any assignment operations. So nobody else can create a copy of it. The only way to get the instance of the class is to call the GetInstancemethod and in the GetInstance method the one instance of the class has been created as a static variable. As per the C++ standard:

Dynamic initialization of a block-scope variable with static storage duration ( or thread storage duration ( is performed the first time control passes through its declaration; such a variable isconsidered initialized upon the completion of its initialization


Destructors (15.4) for initialized objects (that is, objects whose lifetime (6.6.3) has begun) with static storage duration, and functions registered with std::atexit, are called as part of a call to std::exit(21.5). The call t ostd::exit is sequenced before the invocations of the destructors and the registered functions. [Note:Returning from main invokes std::exit(— end note]

So the static variable will be initialized the first time somebody calls the GetInstance and will be safely destroyed at the end. Furthermore, it is thread safe. Why? From the same C++ standard:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

So the static variable will be initialized only once in the thread that reaches that the statement first.

Phew! That was lot to digest but hopefully this article helped you understand the Singleton design pattern.


  1. In the simple example above the constructor was pretty simple. What would you do if the constructor in your code requires some work to do like accessing a database or authenticating the user session?
  2. How will you solve the initial problem of modifying Preference module to be allowed to call once and only once?

Please let me know your answers in the comments below. Cheers!

[codeforces]230A DRAGONS – Sort with custom comparator

Problem statement is here:

The problem is not difficult, what makes it even easier it that even O(n^2) solution is accepted by the judge.

If you consider each Dragon as a struct of strength that it possesses and the bonus it gives then the problem becomes a matter of sorting Dragons that can be killed by the player’s initial strength. I have sorted using a custom comparator which makes life a lot easy. Here is the code:

#include <bits/stdc++.h>

struct Dragon {
  int strength;
  int bonus;
  Dragon(int strength, int bonus) : strength(strength), bonus(bonus) {}

bool comparator(Dragon i, Dragon j) {
  return i.strength < j.strength;

int main() {
  int player_strength;
  int num_dragons;

  std::cin >> player_strength >> num_dragons;

  std::vector<Dragon> dragons;

  for (int i = 0; i < num_dragons; i++) {
    int strength, bonus;
    std::cin >> strength >> bonus;
    dragons.push_back(Dragon(strength, bonus));

  std::sort(dragons.begin(), dragons.end(), comparator);

  for(Dragon dragon : dragons) {
    if(dragon.strength < player_strength) {
    else {
      return 0;


  return 0;

Please let me know in comments if you have found a more optimal way to solve the problem. Cheers!

What to do after Ubuntu upgrade to get WordPress site work again?

Assuming a standard wordpress installation using nginx server, here are the steps to keep wordpress running after upgrading Ubuntu.

1. Edit nginx config file:

sudo vim /etc/nginx/sites-available/{YOUR_SITE}

and modify the line:

fastcgi_pass unix:/run/php/php7.2-fpm.sock;

with correct version of php7.x-fpm.sock (should be one higher than the one in nginx). If you don’t know the version of php-fpm use this command to find out:

sudo apt list --installed | grep php

and look for php<version>-fpm.

2. Install php libraries which were removed as obsolete.


sudo apt-get install php$PHP_VERSION-cli php$PHP_VERSION-cgi php$PHP_VERSION-fpm php$PHP_VERSION-mysql

PHP_VERSION should be the same in the one in nginx config file.

3. Restart php$PHP_VERSION-fpm:

sudo systemctl restart php7.2-fpm.service

4. Restart nginx:

sudo systemctl restart nginx.service