简体   繁体   中英

C - Portable code on Windows and Unix

I'm creating a program and I want it to run on Windows and UNIX. However I've used many functions that are either Windows or Unix specific. For example functions located in #include<unistd.h> and #include <sys/utsname.h> for UNIX and #include <winsock2.h> and #include <windows.h> for Windows. I've got them working independently but I want to merge them together.

Here is an example:

struct timespec start, end; // UNIX code
LARGE_INTEGER clockFrequency; // Windows code
QueryPerformanceFrequency(&clockFrequency); 
LARGE_INTEGER startTime; 
LARGE_INTEGER endTime; 
LARGE_INTEGER elapsedTime; 
//...
QueryPerformanceCounter(&startTime); // Windows code
clock_gettime(CLOCK_REALTIME, &start); // UNIX code
CalculateVectorInputs();
QueryPerformanceCounter(&endTime); // Windows code
clock_gettime(CLOCK_REALTIME, &end); // UNIX code

I'm well aware of ifdef :

#ifdef _WIN32
// Windows code
#else
#ifdef __unix__
// UNIX code
#endif
#endif

but this seems very messy to add all throughout my code, seeing as my program is around 500 lines long. Is there an elegant way to approach this?

A fairly common approach is to write your main application in standard C wherever possible and put all platform specific code in a custom module.

For example, your main application could do

#include "foo_timer.h"

...
foo_timer_t start, end;
foo_get_time(&start);
calculate_stuff();
foo_get_time(&end);
foo_time_delta(start, end, &elapsed);

with no #ifdef s at all.

foo_timer.h might make use of #ifdef to select platform specific typedefs and declarations, but the main implementation will be in separate files:

  • foo_timer_unix.c contains unix-specific code that implements the foo_timer.h interface.
  • foo_timer_windows.c contains windows-specific code that implements the foo_timer.h interface.

When your application is compiled, only one of foo_timer_unix.c and foo_timer_windows.c is compiled and linked into the application. The details of this step depend on your build system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM