如何设置CMake生成仅标头的项目? [英] How do I set up CMake to generate header-only projects?

查看:82
本文介绍了如何设置CMake生成仅标头的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立仅标头的C ++(或C)库项目,但找不到干净的方法。

I want to set up header-only C++ (or C) library projects, but can't find a clean way.

经过一些搜索后,我发现您无法使用 add_library 设置普通库来执行此操作,因为它需要可编译的源文件。
做到这一点的一种方法是改为使用 add_custom_target

After some searches I've found that you can't set up a normal library using add_library to do this because it requires a compilable source file. A way to do this would be to use add_custom_target instead, this way:

# Get all headers (using search instead of explicit filenames for the example)
file( GLOB_RECURSE XSD_HEADERS 
    *.hxx
)
add_custom_target( libsxsd SOURCES ${XSD_HEADERS} )

但这似乎在这里并不完全有效,因为我看不到VS2010中生成的项目中的资源。我不知道这是一个错误还是做错了,或者是否有首选的方法来实现此目的。

But that doesn't seem to work completely here as I can't see the sources in the project generated in VS2010. I don't know if it's a bug or if I'm doing it wrong or if there is a preferred way to do this.

推荐答案

更新:CMake很快将包含一个名为INTERFACE的库目标,非常适合仅标头项目。此功能当前在master分支中。 参考

Update: CMake will soon include a library target called INTERFACE that is ideal for header-only projects. This feature is currently in the master branch. Reference.

建议使用命令 add_custom_target 对我有效(VS2010)。这些文件整齐地列在了我的项目中,但缺点是您无法使用自定义目标定义任何其他包含目录。相反,我现在使用以下内容:

Using the command add_custom_target as you propose works for me (VS2010). The files are neatly listed within my project but it has the drawback that you can't define any "Additional Include Directories" with a custom target. Instead, I now use the following:

add_library(HEADER_ONLY_TARGET STATIC test1.hpp test2.hpp)
set_target_properties(HEADER_ONLY_TARGET PROPERTIES LINKER_LANGUAGE CXX)

这会将您仅标头的项目设置为虚拟存档目标。不用担心,如果您尝试构建它,将不会生成任何实际的二进制文件(至少在VS2010和Xcode 4中不会)。命令 set_target_properties 在那里,因为CMake否则会抱怨它不能仅从.hpp文件推断目标语言。

This sets up your header-only project as a dummy archive target. Don't worry, no actual binaries will be generated if you should try and build it (at least not in VS2010 and Xcode 4). The command set_target_properties is there because CMake will otherwise complain that it cannot infer the target language from .hpp files only.

这篇关于如何设置CMake生成仅标头的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆