用C,C检测Windows或Linux
发布时间:2020-12-16 09:10:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 How do I check OS with a preprocessor directive?????????????????????????????????????16个 我正在编写一个跨平台程序.我希望这个程序在Windows和Linux下运行,所以我有两个不同的代码段用于这两个平台.如果操作系统是Windows,我想要运行第一
参见英文答案 >
How do I check OS with a preprocessor directive?????????????????????????????????????16个
我正在编写一个跨平台程序.我希望这个程序在Windows和Linux下运行,所以我有两个不同的代码段用于这两个平台.如果操作系统是Windows,我想要运行第一个代码段;如果它是Linux,那么我希望第二个代码段运行. 所以我编写了以下代码,但在Windows和Linux上构建时都会出错.我该怎么做才能解决它? #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */ #define OS_Windows 0 #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #elif defined(_WIN32) || defined(WIN32) /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */ #define OS_Windows 1 #include <windows.h> #include <stdio.h> #include <tchar.h> #define DIV 1048576 #define WIDTH 7 #endif int main(int argc,char *argv[]) { if(OS_Windows) { MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); _tprintf (TEXT("There is %*ld %% of memory in use.n"),WIDTH,statex.dwMemoryLoad); } else if(!OS_Windows) // if OS is unix { char cmd[30]; int flag = 0; FILE *fp; char line[130]; int memTotal,memFree,memUsed; flag=0; memcpy (cmd," ",30); sprintf(cmd,"free -t -m|grep Total"); fp = popen(cmd,"r"); while ( fgets( line,sizeof line,fp)) { flag++; sscanf(line,"%*s %d %d %d",&TotalMem,&TotalUsed,&TotalFree); } pclose(fp); if(flag) printf("TotalMem:%d -- TotalUsed:%d -- TotalFree:%dn",TotalMem,TotalUsed,TotalFree); else printf("not foundn"); } return 0; } 解决方法
它通常是这样做的(或多或少):
#ifdef _WIN32 #include <windows.h> #include <stdio.h> #include <tchar.h> #define DIV 1048576 #define WIDTH 7 #endif #ifdef linux #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #endif int main(int argc,char *argv[]) { #ifdef _WIN32 MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); _tprintf (TEXT("There is %*ld %% of memory in use.n"),statex.dwMemoryLoad); #endif #ifdef linux char cmd[30]; int flag = 0; FILE *fp; char line[130]; int TotalMem,TotalFree,TotalUsed; flag=0; memcpy (cmd,30); sprintf(cmd,"free -t -m|grep Total"); fp = popen(cmd,"r"); while ( fgets( line,fp)) { flag++; sscanf(line,&TotalFree); } pclose(fp); if(flag) printf("TotalMem:%d -- TotalUsed:%d -- TotalFree:%dn",TotalFree); else printf("not foundn"); #endif return 0; } 这样,只有linux的代码才能在linux平台上编译,只有windows代码才能在windows平台上编译. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |