0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CMake + clangd で #includeやメソッド等 に赤線が出るときの対処法

0
Last updated at Posted at 2026-07-04

症状

  • ビルドは成功する
  • #include <test/test.h>に赤線が出る
  • Test() が Use of undeclared identifier になる
  • コンパイラは通るのにエディタだけ怒っている

これは clangd が CMake の include パスを取得できていない のが原因。

① CMakeLists.txt

ルートの CMakeLists.txt

cmake_minimum_required(VERSION 3.13)

project(test LANGUAGES CXX)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_library(test INTERFACE)

target_include_directories(test
    INTERFACE
        ${CMAKE_CURRENT_SOURCE_DIR}/include
)

target_compile_features(test
    INTERFACE
        cxx_std_20
)

add_subdirectory(examples/test)

サンプル側

add_executable(test main.cpp)

target_link_libraries(test
    PRIVATE
        test
)

② compile_commands.json を生成する

clangd はcompile_commands.jsonを読んで include パスを取得する。
Visual Studio Generator Visual Studio 18 2026では生成されないことがあるので、Ninja Generator を使う。

③ Ninjaをインストール

winget install Ninja-build.Ninja

④ Developer PowerShell を使う

普通の PowerShell ではNo CMAKE_CXX_COMPILER could be foundになる。
必ずDeveloper PowerShell for Visual Studioから起動する。理由はcl.exeへの PATH が設定されているため。

⑤ CMake生成

cmake -S . -B build ^
-G Ninja ^
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON

すると

build/
    compile_commands.json

が生成される。

⑥ clangd に教える

.vscode/settings.json

{
    "clangd.arguments": [
        "--compile-commands-dir=${workspaceFolder}/build"
    ]
}

⑦ エディタの再起動

これにより対処ができます。

なぜビルドは成功したの?

  • CMake + MSVC はプロジェクト情報(.vcxproj など)を使ってコンパイルするので、include パスを正しく知っている。
  • clangd は Visual Studio のプロジェクトファイルを読み込まず、compile_commands.json を頼りに解析する。

つまり、

  • ビルドはMSVCが正しい情報を持っていたので成功。
  • エディタはclangdが情報不足で、「ヘッダーが見つからない」と誤判断していた。

この違いが今回の原因だった、というわけだね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?