I need to create some API, with which, by calling a function, the correct one for the current operating system will be called.

So I went with that :

main.cpp :

#include "api.h"
int main() {
    helloWorld();
    return 0;
}

api.h :

void helloWorld();

api.cpp :

void helloWorld() {
    #ifdef __gnu_linux__    
        printf("Hello World of Linux");
    #endif
    #ifdef WIN32
        printf("Hello World of Windows");
    #endif
}

But this doesn't satisfy me. When I'll have big functions, such as the one to get all childs of a process under Linux, and many others, I'll have a problem of space, of visibility to maintain the code.

I tryed to include different headers depending on the underlying OS, but this doesn't work very well, I can't have two headers (one for Windows, one for Linux) and only one C++ file.

So, do you know how I could separate the code for Linux and Windows so I end up with two file (one only for Linux and one only for Windows) with one header file that will have a #ifdef condition ? I couldn't make it work ...

有帮助吗?

解决方案

I did it the following way:

main.cpp and api.h does not suffer any modification.

api.cpp:

#ifdef linux
    #include "linux_api.h"
#endif
#ifdef WIN32
    #include "windows_api.h"
#endif

void helloWorld() {
    #ifdef linux
        helloWorld_linux();
    #endif
    #ifdef WIN32
        helloWorld_win32();
    #endif
}

Then you need to provide linux_api.h, linux_api.cpp and windows_api.h, windows_api.cpp. The advantage is that this four files are already platform specific. You only have to create the "glue code" in api.cpp for each function.

linux_api.h:

void helloWorld_linux();

linux_api.cpp:

#include "linux_api.h"

#include <cstdio>

void helloWorld_linux()
{
    std::printf( "Hello world from linux..." );
}

Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top