OpenMP: minimum code

Here’s a minimum code of OpenMP with CMake. The code outputs “OpenMP: ON” if OpenMP is available and “OpenMP: OFF” otherwise.

CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

set(PROJ_NAME OpenMPtest)
PROJECT(${PROJ_NAME})

# Prevent compilation in-source
if( ${CMAKE_BINARY_DIR} STREQUAL ${PROJECT_SOURCE_DIR} )
Message( FATAL_ERROR "In-source build is not allowed. Create a build directory and run cmake in the directory.")
endif()

# enable C++11
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

##############################################
## External libraries
##############################################
# OpenMP
find_package( OpenMP REQUIRED )
if (OPENMP_FOUND)
message(STATUS "build with OpenMP")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}" )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}" )
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
IF (UNIX)
# pthreads is neaded for Linux to enable mutex to compile.
FIND_PACKAGE(Threads REQUIRED)
ENDIF (UNIX)
endif()

##############################################
## Main
##############################################
add_executable(${PROJ_NAME}
main.cpp
)

main.cpp:

#ifdef _OPENMP
	#include <omp.h>
#endif
#include <iostream>

int main()
{
	std::cout << "OpenMP: " << std::flush;
	#ifdef _OPENMP
		std::cout << "ON" << std::endl;
	#else
		std::cout << "OFF" << std::endl;
	#endif
	return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s