我有一个使用CMake作为构建系统的C++项目。在将其移植到macOS时,我需要集成几个Objective-C++文件,但不幸的是,我得到的都是构建错误。我远不是Objective-C++方面的专家,这对我也没有帮助。
为了达到现在的效果,我首先更新了纯C++项目的project定义,使其同时包含C++和Objective-C++:
project(projectFOO LANGUAGES CXX OBJCXX)之后,我将所有'.mm‘Objective-C++源文件及其头文件直接传递到add_library调用中。
然而,当我重新构建cmake项目时,我得到了一堵编译器错误的墙,几乎没有类似下面这样的错误消息:
(...)
In file included from /Users/ram/development/Foo/source/MyNSImage.mm:1:
/Users/ram/development/Foo/include/MyNSImage.h:22:5: error: unknown type name 'CGContextRef'
(...)
/Users/ram/development/Foo/source/MyNSImage.mm:7:81: error: use of undeclared identifier 'nil'
(...)在检查了构建所执行的编译器命令之后,我注意到它在传递-x objective-c++ -g和-std=gnu++11的同时调用了/usr/bin/c++。
之后,我可以通过创建一个只包含Objective-C++文件的库来重现相同的错误,该库的CMake定义如下:
cmake_minimum_required(VERSION 3.16) # Introduces support for OBJC and OBJCXX. See https://cmake.org/cmake/help/v3.16/release/3.16.html
project(projectFOO LANGUAGES CXX OBJCXX)
# (..omit C++ code..)
if(APPLE)
# separate library created just to build the Objective-C++ code
add_library(foo_mac
include/MyNSImage.h
source/MyNSImage.mm
)
target_include_directories(foo_mac
PUBLIC
include
)
endif()
# (..omit more C++ code..)
# here's the C++ library
add_library(foo
${foo_INCLUDES}
${foo_HEADERS}
)
if(APPLE)
# when building on macOS, also link the Objective-C++ lib.
target_link_libraries(foo foo_mac)
endif()在使用-DCMAKE_VERBOSE_MAKEFILE刷新CMake项目并重新构建它之后,下面是foo_mac的编译器命令
(...)
cd /Users/ram/development/Foo/cmake-build-debug/Foo && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -I/Users/ram/development/Foo/include -x objective-c++ -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -fPIC -std=gnu++11 -o CMakeFiles/foo_mac.dir/source/MyNSImage.mm.o -c /Users/ram/development/Foo/source/MyNSImage.mm
(...)有谁知道我可能做错了什么吗?
发布于 2021-11-27 21:22:35
事实证明,根本原因是一个丢失的#import,在最初的Objective-C++模块中,它是通过全局传递的带有-include=${header}编译器定义的预编译头偷偷插入的。
https://stackoverflow.com/questions/70137199
复制相似问题