CMake target_precompile_headers导致重新定义错误

问题描述

在使用Cmakes target_precompile_headers时,我们会遇到很多重新定义错误,例如

/usr/include/c++/8/bits/stringfwd.h:70:37: error: redeFinition of default argument for ‘class _Traits’
/usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h:21:3: error: conflicting declaration ‘typedef struct __mbstate_t __mbstate_t’
/usr/include/x86_64-linux-gnu/bits/types/__locale_t.h:28:8: error: redeFinition of ‘struct __locale_struct’
/usr/include/c++/8/bits/postypes.h:112:7: error: redeFinition of ‘class std::fpos<_StateT>’
/usr/include/c++/8/bits/postypes.h:216:1: error: redeFinition of ‘template<class _StateT> bool std::operator==(const std::fpos<_StateT>&,const std::fpos<_StateT>&)’
/usr/include/c++/8/bits/postypes.h:221:1: error: redeFinition of ‘template<class _StateT> bool std::operator!=(const std::fpos<_StateT>&,const std::fpos<_StateT>&)’
/usr/include/c++/8/iosfwd:76:70: error: redeFinition of default argument for ‘class _Traits’
/usr/include/c++/8/iosfwd:79:70: error: redeFinition of default argument for ‘class _Traits’
/usr/include/c++/8/iosfwd:82:70: error: redeFinition of default argument for ‘class _Traits’

以及无数其他内容,全部来自标准库函数

我们的Cmake设置尽可能基本,我们使用g ++-8。

cmake_minimum_required(VERSION 3.1)
set (CMAKE_CXX_STANDARD 14)
project(VoxelGrid LANGUAGES CXX)
file(GLOB srcfiles 
${PROJECT_SOURCE_DIR}/src/*.h   
${PROJECT_SOURCE_DIR}/src/*.cpp
)
add_executable(VoxelGridTest exe/main.cpp ${srcfiles})
target_include_directories(VoxelGridTest PUBLIC ${PROJECT_SOURCE_DIR}/src)
target_precompile_headers(VoxelGridTest PUBLIC ${PROJECT_SOURCE_DIR}/pchs/pch.h)

我们有一个src和一个pch文件夹。系统是Ubuntu20。看来这个问题应该很普遍,但到目前为止我们什么都没发现。 预编译标头仅为

#pragma once
#include <iostream>

没有别的。

感谢您的任何建议!

解决方法

事实证明这是一个 bug in GCC。 我最终将 pch.h 的内容包含在包含守卫中:

// Not using #pragma once here
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56549
#ifndef My_PCH_GUARD
#define My_PCH_GUARD

#include <iostream>

#endif

另一种解决方案是从源中删除 BOM。