在 CLion 中,头文件库: file“不属于任何项目目标,代码洞察特性可能无法正常工作”

我使用 cmake 命令设置了一个只有头文件的库项目:

add_library(my_library INTERFACE)

我还加了

target_sources(my_library INTERFACE ${MY_LIRBARY_HEADER_FILES})

但是当我打开一个源文件时,我会得到一个警告:

此文件不属于任何项目目标,代码洞察功能可能无法正常工作

我失去了很多功能,比如代码完成。

什么是正确的方法来设置这样的 CLion 提供其通常的功能在一个标题-只有库?

110486 次浏览

Clion takes information about source files from CMake build system. When you add any cpp file to sources list CMake automatically tell about header with same name. So if cpp/h names differs (or you don't have cpp file at all) you should include header manually.

set(Sources my_lib.cpp)
set(Headers header_of_my_lib.h)
add_executable(superlib ${Sources} ${Headers})

If you don't have any executable you can omit last line, CLion will still know about files

You can add the header files to your project like this:

set(SOURCE_FILES main.cpp MyClass1.cpp MyClass1.h MyClass2.cpp MyClass2.h)

You can also set it in multiple steps like so:

set(SOURCE_FILES main.cpp)
set(SOURCE_FILES ${SOURCE_FILES} MyClass1.cpp MyClass1.h)
set(SOURCE_FILES ${SOURCE_FILES} MyClass2.cpp MyClass2.h)

Though as mentioned in the comments, you probably shouldn't be adding the header files to your project at all.

Little background

I was having the same problem, albeit the project was not header-only, nevertheless, the open files from inc folder were throwing the aforementioned warning, even though the CMake file clearly marked that folder to be include_directory.

*.hpp files do not belong to ${SOURCE}

include_directories("${PROJECT_SOURCE_DIR}/inc/")
add_subdirectory(src)
add_executable(${EXECUTABLE_NAME} main.cpp ${SOURCE})

Since this is a perfectly valid CMake file and adding the include files to source files is not idiomatic, I did not want to amend the CMake file.

The solution

As described on the official JetBrains Forum, the CMake file is indeed valid and the warning is shown because of the inability of CLion to properly index header files. The suggested workaround extracted from the link is to right-click the folder and ABC0 | ABC1/Project Sources and Headers.

So, this header isn't includes in executables and CLion notifies you that some code insight features might not work properly. As workaround you can use "Mark directory as" Library Files/Project Source and Headers for folder.

This warning is an IDE issue that Android Studio cannot recognise the current directory if it does not include any source files.

Workaround

Adding am empty source file, e.g empty_xxx.c under the directory in question and adding below line in your corresponding CMakeList.txt

add_library(${TARGET_NAME_XXX} SHARED ${SOME_DIR_HAVING_THIS_WARNING}/empty_xxx.c)

will help get rid of this warning.