Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing cross-platform C++ Code (Windows, Linux and Mac OSX)

This is my first-attempt at writing anything even slightly complicated in C++, I'm attempting to build a shared library that I can interface with from Objective-C, and .NET apps (ok, that part comes later...)

The code I have is -

#ifdef TARGET_OS_MAC   // Mac Includes Here #endif  #ifdef __linux__   // Linux Includes Here   #error Can't be compiled on Linux yet #endif  #ifdef _WIN32 || _WIN64   // Windows Includes Here   #error Can't be compiled on Windows yet #endif  #include <iostream>  using namespace std;  bool probe(){   #ifdef TARGET_OS_MAC     return probe_macosx();   #endif   #ifdef __linux__     return probe_linux();   #endif   #ifdef _WIN32 || _WIN64     return probe_win();   #endif }  bool probe_win(){   // Windows Probe Code Here   return true; }  int main(){    return 1; } 

I have a compiler warning, simply untitled: In function ‘bool probe()’:untitled:29: warning: control reaches end of non-void function - but I'd also really appreciate any information or resources people could suggest for how to write this kind of code better....

like image 359
Lee Hambley Avatar asked Sep 02 '10 12:09

Lee Hambley


People also ask

Are C programs cross-platform?

The language C itself is cross-platform, because you don't directly run C code on machines. The C source code is compiled to assembly, and assembly is the platform specific code. The only non cross-platform part are the compilers and the resulting assembly.

Is C C++ cross-platform?

C++ is cross-platform. You can use it to build applications that will run on many different operating systems.

How do you write a cross-platform program?

Using conditional compilation in C or C++, you can write a program that will use OS-specific features and simply compile differently on each platform. Of course in that case the effort can almost be the same as writing two applications.


1 Answers

instead of repeating yourself and writing the same #ifdef .... lines again, again, and again, you're maybe better of declaring the probe() method in a header, and providing three different source files, one for each platform. This also has the benefit that if you add a platform you do not have to modify all of your existing sources, but just add new files. Use your build system to select the appropriate source file.

Example structure:

include/probe.h src/arch/win32/probe.cpp src/arch/linux/probe.cpp src/arch/mac/probe.cpp 

The warning is because probe() doesn't return a value. In other words, none of the three #ifdefs matches.

like image 134
stijn Avatar answered Sep 29 '22 18:09

stijn