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.

CMake

Create a CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)
project(demo CXX)

add_executable(foo foo.cpp)

if(UNIX)
  find_package(Curses REQUIRED)
  
  target_link_libraries(foo ${CURSES_LIBRARIES})
endif()

Pragma

top of foo.cpp:

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

#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

Alternatives

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.

Tags:

Categories:

Comments

Written by Michael Hirsch, Ph.D. //