Gor*_*ews 2 c unix windows portability
我正在创建一个程序,我希望它能在Windows和UNIX上运行.但是我使用了许多Windows或Unix特有的功能.对于位于例如功能#include<unistd.h>
和#include <sys/utsname.h>
UNIX和 #include <winsock2.h>
以及#include <windows.h>
适用于Windows.我让他们独立工作,但我想将它们合并在一起.
这是一个例子:
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
Run Code Online (Sandbox Code Playgroud)
我很清楚ifdef
:
#ifdef _WIN32
// Windows code
#else
#ifdef __unix__
// UNIX code
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
但是在我的代码中添加所有内容似乎非常混乱,因为我的程序大约有500行.有没有一种优雅的方法来解决这个问题?
一种相当常见的方法是尽可能在标准C中编写主应用程序,并将所有特定于平台的代码放在自定义模块中.
例如,您的主应用程序可以执行
#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);
Run Code Online (Sandbox Code Playgroud)
没有#ifdef
s.
foo_timer.h
可能会使用#ifdef
选择特定于平台的typedef和声明,但主要实现将在单独的文件中:
foo_timer_unix.c
包含实现foo_timer.h
接口的特定于unix的代码.foo_timer_windows.c
包含实现foo_timer.h
接口的特定于Windows的代码.当应用程序被编译,只有一个foo_timer_unix.c
与foo_timer_windows.c
被编译并链接到应用程序.此步骤的详细信息取决于您的构建系统.