Check C or C++ Type Size using CMake

Check C or C++ Type Size using CMake

When building cross-platform C or C++ projects, you may need to know the size of certain data types. The size of primitive types like long, long long, or size_t can differ between architectures, operating systems, or compilers. Detecting these differences at configuration time helps you write portable code that behaves consistently across platforms. This tutorial demonstrates how to check C or C++ type size using CMake.

CMake offers a built-in mechanism to determine the size of a given type: the check_type_size command. It compiles a short test program to evaluate the type's size.

Let's look at a simple example of using it in a CMakeLists.txt file:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

include(CheckTypeSize)

check_type_size("long long" SIZEOF_LONG_LONG)
message(STATUS "HAVE_SIZEOF_LONG_LONG: ${HAVE_SIZEOF_LONG_LONG}")
message(STATUS "SIZEOF_LONG_LONG: ${SIZEOF_LONG_LONG}")
message(STATUS "SIZEOF_LONG_LONG_CODE: ${SIZEOF_LONG_LONG_CODE}")

add_executable(${PROJECT_NAME} main.cpp)

When you run CMake, it performs a series of checks to ensure the necessary headers are available (sys/types.h, stdint.h, stddef.h) and then determines the size of the specified type.

CMake automatically defines several variables. In our case, the variable SIZEOF_LONG_LONG holds the size of the type in bytes, while HAVE_SIZEOF_LONG_LONG indicates whether the check was successful. Additionally, CMake generates a corresponding SIZEOF_LONG_LONG_CODE variable containing the preprocessor definition, which could be used in the generated header file. In general, for any type you test, CMake creates variables following the same pattern: HAVE_<NAME> and <NAME>_CODE.

Output example:

-- HAVE_SIZEOF_LONG_LONG: TRUE
-- SIZEOF_LONG_LONG: 8
-- SIZEOF_LONG_LONG_CODE: #define SIZEOF_LONG_LONG 8

By default, the check_type_size command prints diagnostic messages like:

-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of long long
-- Check size of long long - done

If you're performing several type checks and prefer a quieter configuration phase, you can suppress the verbose messages by setting CMAKE_REQUIRED_QUIET variable before invoking the check:

# ...

set(CMAKE_REQUIRED_QUIET TRUE)

include(CheckTypeSize)

check_type_size("long long" SIZEOF_LONG_LONG)

# ...

Leave a Comment

Cancel reply

Your email address will not be published.