Make C++ code for Visual Studio (Windows) and g++ (Linux)

1 minute read

To quickly write some code in C/C++ for mathematical computations in Windows, you might be using Visual Studio in Windows instead of the Code::Blocks or Eclipse-CDT available on Windows/Mac/Linux. You should also consider Windows Subsystem for Linux. But if you must use a Windows-based C++ compiler, here are a few things to consider to compile your Visual Studio-originated C++ under multi-platform (Windows Mac Linux).

1. Verify command line compilation

In Linux for C++ you would compile with either LLVM-Clang or g++ for your program foo.cpp

clang++ -o foo -std=c++11 foo.cpp -lncurses -lm


g++ -o foo -std=c++11 foo.cpp -lncurses -lm

Then type ./foo to run your program.

2. Set environment conditionals

Here we modify the “include” part of our code to be appropriate for the operating system we’re compiling for. Let’s assume the original Windows Visual Studio code had

#include <conio.h>

In Linux, we use ncurses instead of conio. So modify to:

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

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <math.h>

note the #include "stdafx.h" is a file used by Visual Studio to set compilation preferences.

remember the -lncurses and -lm we typed to compile? This tells the compiler to link to math.h and ncurses.h (using math functions and outputting text to the console).

3. Writing files with path separator

fstream allows writing files to disk–but Windows and Mac/Linux use different directory slashes.  You can set ifdefs, or use Boost path::preferred _separator

#include <boost/filesystem.hpp>
#include <iostream>

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

That will print / or \ depending on your system.

Leave a comment