target_precompile_headers with MacOs and Objective-C++ (.mm) files


When I use target_precompile_headers in my project the compilation of my mm-files fail with the following error:
error: Objective-C 1 was disabled in PCH file but is currently enabled.
However, when I generate an Xcode - project, compilation in Xcode works fine.

I saw that target_precompile_headers creates the parameter -include-pch in the call of the compiler on command line. Xcode does that not! When I call the compiler myself without that -include-pch parameter on the mm-file, like Xcode does, everything works fine.
When I use “add_compile_options(-Xclang -include -Xclang ${PROJECT_SOURCE_DIR}/stdafx.h)” instead of “target_precompile_headers”, it also works fine.
My CMakeLists.txt is this:

cmake_minimum_required(VERSION 3.10)


add_executable(testlib lib.h lib.cpp

#Does not work
target_precompile_headers(testlib PRIVATE stdafx.h)
#Works for my, -Xclang depends on the compiler, Cmake is using
add_compile_options(-Xclang -include -Xclang ${PROJECT_SOURCE_DIR}/stdafx.h)

My stdafx.h file looks like that:

#pragma once
#include <iostream>
#ifdef __objc__
    #import <Foundation/Foundation.h>

Is this a bug in CMake?

Best regards,

Probably. I don’t know how much Obj-C / Obj-C++ testing the PCH feature received. @brad.king Do you know?

target_precompile_headers was added in CMake 3.16, which also added support for enabling OBJC and OBJCXX as their own languages. One needs to do that to use PCH and ObjC++ together. Try

cmake_minimum_required(VERSION 3.16)

That worked.
Probably it was useful to add this hint to the documentation of target_precompile_header?

However, thanks a lot four your help,