Keep g++ as default compiler but also export the clang command, in order to add include directory to path

42 views Asked by At

I want to use clangd as my linter, g++ as my compiler and CMake as my build system. My project has the following structure:

MyProject
├── build
│   ├── ...
├── CMakeLists.txt
├── compile_commands.json -> build/compile_commands.json
├── include
│   └── sorting
│       └── Sorting.h
├── main.cpp
└── src
    └── sorting
        └── Sorting.cpp

It is a good practice to separate header and implementation files, which is why I have the include and src directories. It's also a good practice to add the include directory to path. This way, I can do #include "Sorting.h", regardless of the specific hierarchy. So far I have produced the following CMake code to achieve this:

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
cmake_minimum_required(VERSION 3.27)

project(DSA
  DESCRIPTION "My DSA Implementations"
  LANGUAGES CXX)


add_library(sorting STATIC src/sorting/Sorting.cpp include/sorting/Sorting.h)
target_include_directories(sorting PUBLIC include)

add_executable(main main.cpp)
target_link_libraries(main PUBLIC sorting)

However, this only exports the c++ command to compile-commands.json and my clangd linter remains broken. Is there a way to achieve what I want? The simplest solution I can think of, is to create another CMake build, where the compiler is set to clang++.

By the way, I have a .clang-tidy setup file, which I generated using clang-tidy -checks=bugprone-\*,modernize-\*,performance-\*,readability-\*,cppcoreguidelines-\* --dump-config > .clang-tidy. Could this be the source of my troubles?

1

There are 1 answers

0
Kotaka Danski On

The reason for my failure was an improper inclusion of the include folder. The correct usage is as follows:

target_include_directories(sorting PUBLIC include)
#include "sorting/Sorting.h" // in main.cpp

or,

target_include_directories(sorting PUBLIC include/sorting)
#include "Sorting.h" // in main.cpp

Thanks to @drescherjm for pointing out my mistake and providing additional tips in the comments.