Tell CMake to use C++ compiler for C files coming

2019-01-06 23:16发布

问题:

This is similar to Force CMake to use C++ compiler for C files with Visual Studio, but its not quite the same. Its not the same because a its CMake file causing the failure; and I'm working on nearly every modern platform, from BSDs and OS X through Solaris and Unix.

I tried to avoid useless checks being performed by CMake:

project(cryptopp, CXX)

Here's what happens when I attempt to generate the makefile:

$ cmake .
-- Check if the system is big endian
-- Searching 16 bit integer
-- Check size of unsigned short
CMake Error at /usr/share/cmake-2.8/Modules/CheckTypeSize.cmake:82 (try_compile):
  Unknown extension ".c" for file

    /home/jeffrey/cryptopp/CMakeFiles/CheckTypeSize/CMAKE_SIZEOF_UNSIGNED_SHORT.c

  try_compile() works only for enabled languages.  Currently these are:

    CXX

  See project() command to enable other languages.
Call Stack (most recent call first):
  /usr/share/cmake-2.8/Modules/CheckTypeSize.cmake:167 (__check_type_size_impl)
  /usr/share/cmake-2.8/Modules/TestBigEndian.cmake:27 (CHECK_TYPE_SIZE)
  CMakeLists.txt:49 (TEST_BIG_ENDIAN)

We don't have any C files in our project, so we should be safe with project(cryptopp, CXX) (if I am reading cmake --help-command project correctly).

The cited question talks about project files, but not CMake files.

How do I tell CMake to use C++ compiler for all files, including its own CMake files?


I'm on Ubuntu 12 LTS, and it provides:

$ cmake --version
cmake version 2.8.7

回答1:

There are ways to add .c as a valid file extension for the CXX compiler. Even this being very advanced CMake stuff, you may need - if you are bound to support older versions of CMake - a "make rules overwrite script" anyway.

So I've successfully tested the following:

CryptoppMakeRulesOverwrite.cmake

list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS c)

CMakeLists.txt

cmake_minimum_required(VERSION 2.8.7 FATAL_ERROR)

set(CMAKE_USER_MAKE_RULES_OVERRIDE "CryptoppMakeRulesOverwrite.cmake")

project(cryptopp CXX)

include(CheckTypeSize)
CHECK_TYPE_SIZE("unsigned short" CMAKE_SIZEOF_UNSIGNED_SHORT)

As @Tsyvarev has commented check_type_size() supports a LANGUAGE parameter, but unfortunately not for CMake version 2.8.7. But this older version does already support CMAKE_USER_MAKE_RULES_OVERRIDE.

So I'm still wondering if not the best solution would be to go to a newer version of CMake (forcing some users of older CMake versions to upgrade). Or writing your own try_compile() snippets.

References

  • How to add in a CMake project a global file extension (*.pde) to GCC which is treated like C++ code
  • Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake


标签: cmake