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....
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.
C++ is cross-platform. You can use it to build applications that will run on many different operating systems.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With