C++跨平台通过宏定义判断当前操作系统windows,linux和编译器

int main()
{
	//系统宏
#ifdef __ANDROID__
	string port("/dev/ttyUSB1");
#elif __linux__
	string port("/dev/ttyUSB0");
#elif _WIN32
	string port("Com3");
#endif

	//编译器宏
#ifdef _MSC_VER
	cout << "hello MSVC" << endl;
#elif __GNUC__
	cout << "hello gcc" << endl;
#elif __BORLANDC__
	cout << "hello Borland c++" << endl;
#endif
}

以上代码在vs2019中测试没有问题。

其中__ANDROID__宏在安卓ndk开发时候会用到

在CMakeLists.txt中也有宏区分不同操作系统:

if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    message(STATUS "Configuring on/for Linux")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
    message(STATUS "Configuring on/for macOS")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows")
    message(STATUS "Configuring on/for Windows")
elseif(CMAKE_SYSTEM_NAME STREQUAL "AIX")
    message(STATUS "Configuring on/for IBM AIX")
else()
    message(STATUS "Configuring on/for ${CMAKE_SYSTEM_NAME}")
endif()

 

你可能感兴趣的:(C++,cmake,系统宏,编译器,linux,操作系统)