Writing C++ code to work in both Visual Studio (Windows) and g++ (Linux)

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

I start out by compiling with the command line so that I feel I know what options are being used to compile–so that if I send my code to a friend, they can compile it too. 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

or

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> 
#endif

#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.