CMake C++ code for Visual Studio Windows and g++ Linux

CMake easily supports platform / compiler / language agnostic program builds. For example, use a C++ across Windows, MacOS and Linux easily with minimal program modifications as in the example below.


Create a CMakeLists.txt:

add_executable(foo foo.cpp)

  find_package(Curses REQUIRED)

  target_link_libraries(foo ${CURSES_LIBRARIES})


top of foo.cpp:

#ifdef _WIN32
#include "stdafx.h"
#include <conio.h>
#else // LINUX MAC
#include <ncurses.h>

#include <iostream>
  • #include "stdafx.h" is used by Visual Studio to set compilation preferences.

Path separators

fstream allows writing files to disk. Some operations need to manage Windows and Mac/Linux different directory slashes.

Use C++17 std::filesystem::path::preferred _separator to manage platform-agnostic path separators. Even better, akin to Python pathlib, use std::filesystem::path instead of messing around with strings for filenames.

C++17 filesystem works on GCC ≥ 8 and Clang easily using CMake.

#include <filesystem>
#include <iostream>

int main() {
    std::cout << std::filesystem::path::preferred_separator << std::endl;

That simple code prints:

  • \ Windows
  • / Mac, Linux


Consider Windows Subsystem for Linux for easier Windows support. Sometimes, WSL could save very large amounts of work to get programs working for Windows users.