Programing

전 처리기 지시문으로 OS를 어떻게 확인합니까?

lottogame 2020. 5. 26. 07:44
반응형

전 처리기 지시문으로 OS를 어떻게 확인합니까?


컴파일 된 운영 체제에 따라 다른 작업을 수행하려면 코드가 필요합니다. 나는 이와 같은 것을 찾고있다 :

#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif

이것을 할 수있는 방법이 있습니까? 같은 일을하는 더 좋은 방법이 있습니까?


미리 정의 된 매크로 OS 용 사이트는 검사의 매우 완전한 목록이 있습니다. 다음은 발견 된 곳으로 연결되는 링크입니다.

윈도우

_WIN32   32 비트 및 64 비트
_WIN64   64 비트 만

유닉스 (Linux, * BSD, Mac OS X)

이 점검을 사용하는 함정 중 일부에 대해서는이 관련 질문참조 하십시오.

unix
__unix
__unix__

맥 OS X

__APPLE__
__MACH__

둘 다 정의됩니다. 둘 중 하나를 확인하면 작동합니다.

리눅스

__linux__
linux폐기 됨 (POSIX 호환 아님)
__linux폐기 됨 (POSIX 호환 아님)

FreeBSD

__FreeBSD__


Windows에서 GCC 정의 표시 :

gcc -dM -E - <NUL:

Linux에서 :

gcc -dM -E - </dev/null

MinGW에서 사전 정의 된 매크로 :

WIN32 _WIN32 __WIN32 __WIN32__ __MINGW32__ WINNT __WINNT __WINNT__ _X86_ i386 __i386

UNIX에서 :

unix __unix__ __unix

nadeausoftwareLambda Fairy의 답변을 기반으로 합니다.

#include <stdio.h>

/**
 * Determination a platform of an operation system
 * Fully supported supported only GNU GCC/G++, partially on Clang/LLVM
 */

#if defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows
#elif defined(_WIN64)
    #define PLATFORM_NAME "windows" // Windows
#elif defined(__CYGWIN__) && !defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)
#elif defined(__ANDROID__)
    #define PLATFORM_NAME "android" // Android (implies Linux, so it must come first)
#elif defined(__linux__)
    #define PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other
#elif defined(__unix__) || !defined(__APPLE__) && defined(__MACH__)
    #include <sys/param.h>
    #if defined(BSD)
        #define PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
    #endif
#elif defined(__hpux)
    #define PLATFORM_NAME "hp-ux" // HP-UX
#elif defined(_AIX)
    #define PLATFORM_NAME "aix" // IBM AIX
#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_IPHONE == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_MAC == 1
        #define PLATFORM_NAME "osx" // Apple OSX
    #endif
#elif defined(__sun) && defined(__SVR4)
    #define PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana
#else
    #define PLATFORM_NAME NULL
#endif

// Return a name of platform, if determined, otherwise - an empty string
const char *get_platform_name() {
    return (PLATFORM_NAME == NULL) ? "" : PLATFORM_NAME;
}

int main(int argc, char *argv[]) {
    puts(get_platform_name());
    return 0;
}

GCC 및 clang을 사용하여 테스트 한 결과 :

  • 데비안 8
  • 윈도우 (MinGW)
  • 윈도우 (Cygwin)

대부분의 경우 주어진 기능의 존재 여부를 확인하는 것이 좋습니다. 예를 들어, 함수 pipe()가 존재하는지 여부입니다.


#ifdef _WIN32
// do something for windows like include <windows.h>
#elif defined __unix__
// do something for unix like include <unistd.h>
#elif defined __APPLE__
// do something for mac
#endif

Microsoft C / C ++ 컴파일러 (MSVC) 사전 정의 된 매크로는 여기에서 찾을 수 있습니다.

https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros

나는 당신이 찾고 있다고 생각합니다 :

_WIN32-컴파일 대상이 32 비트 ARM, 64 비트 ARM, x86 또는 x64 인 경우 1로 정의됩니다. 그렇지 않으면 undefined
_WIN64-컴파일 대상이 64 비트 ARM 또는 x64 인 경우 1로 정의됩니다. 그렇지 않으면 정의되지 않습니다.

gcc 컴파일러 사전 정의 된 매크로는 다음에서 찾을 수 있습니다.

http://gcc.gnu.org/onlinedocs/cpp/Predefined-Macros.html

나는 당신이 찾고 있다고 생각합니다 :

__GNUC__
__GNUC_MINOR__
__GNUC_PATCHLEVEL__

Do a google for your appropriate compilers pre-defined.


There is no standard macro that is set according to C standard. Some C compilers will set one on some platforms (e.g. Apple's patched GCC sets a macro to indicate that it is compiling on an Apple system and for the Darwin platform). Your platform and/or your C compiler might set something as well, but there is no general way.

Like hayalci said, it's best to have these macros set in your build process somehow. It is easy to define a macro with most compilers without modifying the code. You can simply pass -D MACRO to GCC, i.e.

gcc -D Windows
gcc -D UNIX

And in your code:

#if defined(Windows)
// do some cool Windows stuff
#elif defined(UNIX)
// do some cool Unix stuff
#else
#    error Unsupported operating system
#endif

On MinGW, the _WIN32 define check isn't working. Here's a solution:

#if defined(_WIN32) || defined(__CYGWIN__)
    // Windows (x86 or x64)
    // ...
#elif defined(__linux__)
    // Linux
    // ...
#elif defined(__APPLE__) && defined(__MACH__)
    // Mac OS
    // ...
#elif defined(unix) || defined(__unix__) || defined(__unix)
    // Unix like OS
    // ...
#else
    #error Unknown environment!
#endif

For more information please look: https://sourceforge.net/p/predef/wiki/OperatingSystems/


Use #define OSsymbol and #ifdef OSsymbol where OSsymbol is a #define'able symbol identifying your target OS.

Typically you would include a central header file defining the selected OS symbol and use OS-specific include and library directories to compile and build.

You did not specify your development environment, but I'm pretty sure your compiler provides global defines for common platforms and OSes.

See also http://en.wikibooks.org/wiki/C_Programming/Preprocessor


Just to sum it all up, here are a bunch of helpful links.


Sorry for the external reference, but I think it is suited to your question:

C/C++ tip: How to detect the operating system type using compiler predefined macros


Some compilers will generate #defines that can help you with this. Read the compiler documentation to determine what they are. MSVC defines one that's __WIN32__, GCC has some you can see with touch foo.h; gcc -dM foo.h


You can use pre-processor directives as warning or error to check at compile time you don't need to run this program at all just simply compile it .

#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
    #error Windows_OS
#elif defined(__linux__)
    #error Linux_OS
#elif defined(__APPLE__) && defined(__MACH__)
    #error Mach_OS
#elif defined(unix) || defined(__unix__) || defined(__unix)
    #error Unix_OS
#else
    #error Unknown_OS
#endif

#include <stdio.h>
int main(void)
{
    return 0;
}

I did not find Haiku definition here. To be complete, Haiku-os definition is simple __HAIKU__


You can use Boost.Predef which contains various predefined macros for the target platform including the OS. Yes boost is often thought as a C++ library, but this one is a preprocessor header that works with C as well

This library defines a set of compiler, architecture, operating system, library, and other version numbers from the information it can gather of C, C++, Objective C, and Objective C++ predefined macros or those defined in generally available headers. The idea for this library grew out of a proposal to extend the Boost Config library to provide more, and consistent, information than the feature definitions it supports. What follows is an edited version of that brief proposal.

For example

#include <boost/predef.h>

#if defined(BOOST_OS_WINDOWS)
#elif defined(BOOST_OS_ANDROID)
#elif defined(BOOST_OS_LINUX)
#elif defined(BOOST_OS_BSD)
...
#endif

I wrote an small library to get the operating system you are on, it can be installed using clib (The C package manager), so it is really simple to use it as a dependency for your projects.

Install

$ clib install abranhe/os.c

Usage

#include <stdio.h>
#include "os.h"

int main()
{
    printf("%s\n", operating_system());
    // macOS
    return 0;
}

It returns a string (char*) with the name of the operating system you are using, for further information about this project check it out the documentation on Github.

참고URL : https://stackoverflow.com/questions/142508/how-do-i-check-os-with-a-preprocessor-directive

반응형