дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
A C or C++ function declared but never defined only failed at link time. A new inspection, Function declared but never defined (C/C++, weak warning), reports a prototype when clangd's go to definition finds only the declaration itself. Pure virtual, defaulted and deleted functions, operators, macro calls and Qt signals are left out. Quick fixes: Create Definition in the header's source file, and Implement Inline. Co-authored-by: yohannlog <[email protected]>
184 рядки
21 KiB
Plaintext
184 рядки
21 KiB
Plaintext
---
|
||
title: "C and C++"
|
||
description: "Code intelligence with clangd, CMake and Makefile run configurations, single-file runs and native debugging with lldb-dap, CodeLLDB or GDB."
|
||
---
|
||
|
||
OpenIDEA supports C, C++, Objective-C and Objective-C++ through [clangd](https://clangd.llvm.org). Highlighting, folding and the outline work without any setup. Completion, navigation, diagnostics and refactorings come from clangd, and how good they are depends on clangd knowing your compile flags. For the other languages, see the [support matrix](/en/languages/index).
|
||
|
||
| Language | Extensions | Language server | Debugger (default) |
|
||
| ------------- | ----------------------------------------------------------------------------------------------------- | --------------- | ------------------ |
|
||
| C | `.c`, `.h` | clangd | lldb-dap |
|
||
| C++ | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, `.hh`, `.hxx`, `.h++`, `.ipp`, `.tpp`, `.inl`, `.ixx`, `.cppm` | clangd | lldb-dap |
|
||
| Objective-C | `.m` | clangd | lldb-dap |
|
||
| Objective-C++ | `.mm` | clangd | lldb-dap |
|
||
|
||
`.h` files open as C. To treat headers as C++, or Objective-C headers as Objective-C so the outline shows their `@interface` and `@protocol` blocks, change the association in **Settings › Editor › File Types**.
|
||
|
||
The outline of Objective-C files lists `@interface`, `@implementation` and `@protocol` blocks, categories, methods by selector (`initWithName:age:`), properties, instance variables, C functions and `#pragma mark` labels. Objective-C++ files use the same grammar, so their C++ declarations outside Objective-C blocks (namespaces, classes) are not listed.
|
||
|
||
## Language server
|
||
|
||
clangd starts with `--background-index --header-insertion=never` for C and C++, so it indexes the whole project in the background and never adds `#include` lines on its own.
|
||
|
||
clangd finds the workspace root by looking up from the file for one of these files: `compile_commands.json`, `compile_flags.txt`, `.clangd`, `CMakeLists.txt`, `meson.build` or `Makefile`. Objective-C and Objective-C++ only use `compile_commands.json`, `compile_flags.txt` and `.clangd`.
|
||
|
||
### Compile flags
|
||
|
||
clangd needs the flags each file is compiled with. Without them it guesses, and you see false errors about missing headers or unknown macros. Provide one of:
|
||
|
||
- **`compile_commands.json`**: a compilation database. CMake writes it into the build directory when `CMAKE_EXPORT_COMPILE_COMMANDS` is on, and the CMake configurations OpenIDEA creates always pass `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` (see [CMake](#cmake)). For Make-based projects, tools such as Bear can generate one.
|
||
- **`compile_flags.txt`**: one flag per line, applied to every file. Good for small projects.
|
||
- **`.clangd`**: clangd's own configuration file, for example to point `CompilationDatabase` at a build directory.
|
||
|
||
<Tip>
|
||
With CMake profiles or enabled presets, clangd reads the **active profile's** `compile_commands.json`: OpenIDEA starts it with `--compile-commands-dir` set to that profile's build directory, and restarts it when you choose another profile in the title bar, or once the active profile's directory is configured for the first time. A `compile_commands.json` at the project root, a `.clangd` file naming a `CompilationDatabase`, or a `--compile-commands-dir` in the server's arguments take precedence. Otherwise clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each; for another directory, add a `.clangd` file with `CompileFlags: { CompilationDatabase: <dir> }`.
|
||
</Tip>
|
||
|
||
### Functions without a definition
|
||
|
||
A function declared without a body (in a header, a namespace or a class) that clangd finds no definition for is greyed out, with "Function 'name' is declared but never defined" on hover. Pure virtual, defaulted and deleted functions, operators and the `signals:` of Qt classes (moc writes them) are left out. Nothing is decided while clangd is still indexing, since a definition in a file it has not indexed yet would look missing.
|
||
|
||
It is the **Function declared but never defined** inspection (C/C++ group of **Settings › Editor › Inspections**, a weak warning by default), so it also shows in the Problems tool window. Its fixes, under `⌥↵` / `Alt+Enter`:
|
||
|
||
- **Create Definition** writes an empty definition, qualified with its namespaces and classes and without default arguments, at the end of the header's source file (found as **Switch Header/Source** finds it), or of the file itself when it is a source file, and puts the caret in its body. Not offered for templates.
|
||
- **Implement Inline** gives the declaration an empty body where it is (adding `inline` to a free function in a header).
|
||
|
||
### Xcode projects
|
||
|
||
In a folder with a `buildServer.json` (the build server config for Xcode projects, see [Swift › Xcode projects](/en/languages/swift#xcode-projects)), C, C++, Objective-C and Objective-C++ files use sourcekit-lsp instead of clangd. sourcekit-lsp gets each file's flags from the build server and passes them to its own clangd, so headers on the target's search paths and the generated `<Module>-Swift.h` resolve. Swift and C-family files of the project share one sourcekit-lsp. A build server config only under `.bsp/` is not used for this, because sbt, Mill and Bazel write that folder too. Without `buildServer.json`, or when sourcekit-lsp is not installed, clangd serves the files as described above.
|
||
|
||
### Live templates
|
||
|
||
Live templates for C and C++ include `main`, `fori`, `iter` (range-based `for`), `itit`, `incg` (an include guard named after the file), `cl`, `nsp`, `lam`, `cout`, `uptr` and `test` (GoogleTest) / `tc` (Catch2 or doctest). They are listed under **Settings › Editor › Live Templates**.
|
||
|
||
### Header and source
|
||
|
||
**Switch Header/Source** (in Find Action; `F10`, `⌥O` / `Alt+O` in the VS Code keymaps) opens the counterpart of the current file: `Foo.m` or `Foo.cpp` from `Foo.h`, and back. It asks clangd first (`textDocument/switchSourceHeader`, which also finds a source file in another folder). When clangd is not running for the file or has no answer, it opens a project file with the same name and a counterpart extension, preferring the same folder. **Related Symbol…** (`⌃⌘↑` / `Ctrl+Alt+Home`) lists every match by name instead.
|
||
|
||
### Generate
|
||
|
||
**Generate…** (`⌘N` / `Alt+Insert`) in a C++ class or struct offers **Constructor**, **Getter**, **Setter**, **Getter and Setter**, **Equality Operators** (`operator==` and `operator!=`) and **Stream Output Operator** (`operator<<`, adding `#include <ostream>` when needed), beside clangd's own generate actions. The fields are chosen in a dialog, and the members are written inline at the end of the class, in a `public:` section. Accessors are named after the field without its `m_`, `_` or trailing `_` (`getName`, `isEnabled`, `setName`), and return scalars and pointers by value, other types by `const &`.
|
||
|
||
### Apple's clangd
|
||
|
||
The `clangd` that ships with Xcode and the Command Line Tools does not run clang-tidy. When a project has a `.clang-tidy` file and the IDE is using Apple's clangd, it shows a warning with an **Install** button that installs the LLVM build instead.
|
||
|
||
### Preprocessor
|
||
|
||
Code that an `#if`, `#ifdef` or `#else` branch leaves out for the current compile flags is greyed out, as clangd reports it. **View › Show Macro Expansion** (in Find Action) shows what the macro at the caret expands to, from clangd's hover; **Expand macro** under `⌥↵` / `Alt+Enter` replaces the macro with its expansion in the code.
|
||
|
||
## Setup
|
||
|
||
**File › New › Project › C/C++** creates a CMake project in C or C++: an **Executable** (`src/main.cpp` or `src/main.c`) or a **Library**, static or shared (`include/<name>.h` and `src/<name>.cpp` or `.c`, the `include` folder public to the targets that link it). A shared library exports all its symbols on Windows too (`CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS`).
|
||
|
||
When clangd is missing, opening a C or C++ file shows a "clangd is not installed" notification with **Install**. You can also install it from **Settings › Languages & Frameworks › Language Servers**.
|
||
|
||
| Tool | How it is installed | Notes |
|
||
| -------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||
| clangd | Downloaded from the `clangd/clangd` GitHub releases into the IDE's tools folder | Prebuilt for macOS, Linux x64 and Windows x64. On other platforms, install clangd yourself (for example `apt install clangd`). |
|
||
| CodeLLDB | Downloaded from the `vadimcn/codelldb` GitHub releases | Optional, see [Debugging](#debugging). |
|
||
| lldb-dap | Not installed by the IDE | Comes with LLVM (`brew install llvm`). On macOS the IDE also finds Xcode's copy through `xcrun -f lldb-dap`. |
|
||
| GDB | Not installed by the IDE | Needs GDB 14 or newer. |
|
||
|
||
A clangd or debugger already on your `PATH` is used as is. To use a specific binary, select it on the tool's page in **Settings › Languages & Frameworks › Language Servers**.
|
||
|
||
The compiler is not managed by the IDE. Single-file runs look for `clang`, `gcc` or `cc` (C) and `clang++`, `g++` or `c++` (C++) on `PATH`.
|
||
|
||
## Build, run and test
|
||
|
||
### CMake
|
||
|
||
For every `CMakeLists.txt` project, OpenIDEA creates run configurations:
|
||
|
||
- **CMake Configure**: `cmake -S . -B <build dir> -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` (plus `-DCMAKE_BUILD_TYPE=Debug` for a new build directory).
|
||
- **CMake Build**: `cmake --build <build dir>`. It runs the configure step first when the build directory is not configured yet.
|
||
- **CTest**: `ctest --test-dir <build dir> --output-on-failure`, after a build. Each test CTest runs is listed in the test tree, with the output of a failed test.
|
||
- **Build <target>** for every executable and library target (static, shared, module or object), and one run configuration per executable target. Running a target builds it first.
|
||
|
||
The targets come from CMake's File API, so they appear after the first configure. Interface libraries, utility targets (such as Qt's `*_autogen`) and the targets CMake adds itself (`ZERO_CHECK`, `ALL_BUILD`) get no configuration. Nested CMake projects (for example in a folder that holds several repositories) get their own set of configurations.
|
||
|
||
Without saved profiles or enabled presets, the IDE uses every subdirectory of the project that contains a `CMakeCache.txt`, or `build/` when there is none.
|
||
|
||
**Reload CMake Project** (in **Build › CMake**, Find Action and the CMake profile switcher in the title bar) configures the active profile again, which refreshes its targets and `compile_commands.json`. **Reset Cache and Reload CMake Project** first deletes the build directory's `CMakeCache.txt` and `CMakeFiles`. The configure output shows in the Run window.
|
||
|
||
#### CMake profiles
|
||
|
||
To control the build directories yourself, add profiles in **Settings › Build, Execution, Deployment › CMake**, laid out as in CLion: one list holds the saved profiles and the presets, with **Add**, **Remove**, **Copy** (<kbd>Ctrl+D</kbd>), **Move Up** and **Move Down**. Each profile has:
|
||
|
||
| Field | Meaning |
|
||
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||
| Enable profile | A disabled profile stays in the list, greyed, and is not used. |
|
||
| Name | Shown in the profile switcher. |
|
||
| Build type | `Debug`, `Release`, `RelWithDebInfo`, `MinSizeRel` or your own (passed as `CMAKE_BUILD_TYPE`). Empty is CLion's **Default**: no build type, no `--config`. |
|
||
| Toolchain | **Use Default** (the first toolchain) or one of [Toolchains](#toolchains). |
|
||
| Generator | Optional `-G` value, for example `Ninja`, `Unix Makefiles`, `MinGW Makefiles`, `Ninja Multi-Config`, `Visual Studio 17 2022` or `Xcode`. Empty lets CMake decide. |
|
||
| CMake options | Extra arguments for the configure step. |
|
||
| Build directory | Empty means `cmake-build-<build type>`, for example `cmake-build-debug` (`cmake-build-default` for the Default build type). |
|
||
| Build options | Extra arguments for `cmake --build`; arguments after `--` go to the native build tool. |
|
||
| Cache variables | The build directory's `CMakeCache.txt` once configured (**Show advanced** for all). Editing a value adds `-DNAME:TYPE=value` to the CMake options, shown in bold; **Revert** removes it. |
|
||
| Environment | Set for configure, build, test and run. |
|
||
|
||
As in CLion, only the **active profile** builds and runs. Pick it in the profile switcher of the title bar, next to the run configuration chooser (or with **Select CMake Profile…**); without a choice the first enabled profile is active. The run configurations keep the same ids whichever profile is active, so their customizations follow a switch. Changing the generator of an existing build directory clears its CMake cache on the next configure.
|
||
|
||
#### CMake presets
|
||
|
||
A `CMakePresets.json` or `CMakeUserPresets.json` at the project root lists each visible configure preset whose `condition` holds after the saved profiles. As in CLion, a preset is read-only and **disabled until you enable it**; copy it to get an editable profile.
|
||
|
||
- **CMake Configure** runs `cmake --preset <name> -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`. The preset's `binaryDir` is the build directory; without one, the IDE adds `-B build/<name>`.
|
||
- **CMake Build** and **Build <target>** run `cmake --build --preset <build preset>` with the first build preset of that configure preset. Without one they build the directory, like a profile.
|
||
- **CTest** runs `ctest --preset <test preset>` the same way.
|
||
- The preset's `environment` is set for the run configurations too. Its `CMAKE_BUILD_TYPE`, else the `configuration` of its build preset (multi-config generators), picks the configuration of the targets (default `Debug`).
|
||
- CLion's vendor field picks the toolchain: `"vendor": { "jetbrains.com/clion": { "toolchain": "MinGW" } }`.
|
||
- Nested CMake projects use their own presets; the profiles of the settings only apply to the root project.
|
||
|
||
The IDE follows `include`, `inherits` and conditions (`equals`, `inList`, `matches`, `anyOf`, `not`…), and expands macros such as `${sourceDir}`, `${presetName}` and `$env{NAME}`. A file it cannot read (invalid JSON, duplicate names, inheritance cycle) is skipped, and the CMake settings page shows why. **Use CMakePresets.json** turns presets off altogether.
|
||
|
||
#### Toolchains
|
||
|
||
**Settings › Build, Execution, Deployment › Toolchains** lists the toolchains for every project; the first is the default. A toolchain is **System** (tools from the paths you give, else from `PATH`) or **MinGW** (a MinGW or MSYS2 directory: its `bin` goes first on `PATH`, with `gcc`, `g++`, `mingw32-make` and `gdb` from there, and the `MinGW Makefiles` generator unless the build tool is Ninja). **Detect MinGW** adds the MSYS2 environments and MinGW installs found in their usual places.
|
||
|
||
Each tool can be set: **CMake** (configure, build, and the `ctest` next to it), **Build Tool** (`CMAKE_MAKE_PROGRAM`), **C Compiler** and **C++ Compiler** (`CMAKE_C_COMPILER`, `CMAKE_CXX_COMPILER`), and **Debugger** (preferred over lldb-dap for the profile's run configurations). Under each one the page shows the executable it resolves to and its version. A toolchain never overrides what the profile sets itself: a variable among its CMake options or its preset's `cacheVariables`, the compilers and build tool when it names a toolchain file, and the build tool when its generator cannot use it (Visual Studio, Xcode, or Ninja with a make).
|
||
|
||
#### Test executables
|
||
|
||
An executable target whose sources include GoogleTest (`gtest/…`, `gmock/…`), Catch2 v3 (`catch2/catch_…`) or doctest is a test configuration: running it lists its tests in the test tree, with each failure's message and location. Catch2 runs with `--reporter teamcity` and doctest with `--duration=true` so each test is reported, unless the configuration chooses its own reporter or duration option.
|
||
|
||
In a source of a test executable, `TEST`, `TEST_F`, `TEST_P`, `TYPED_TEST`, `TEST_CASE`, `SCENARIO` and `TEST_CASE_METHOD` get a gutter run icon. It runs that test only (`--gtest_filter`, a Catch2 test spec, doctest's `--test-case`) and turns green or red with its last result.
|
||
|
||
### Makefiles
|
||
|
||
A `Makefile`, `makefile` or `GNUmakefile` gives one `make <target>` configuration per target. `test` and `check` targets are marked as tests.
|
||
|
||
### Single files
|
||
|
||
A C or C++ file with a `main` function can be run without a build system: use **Run Context Configuration** (`⌃⇧R` / `Ctrl+Shift+F10`) or **Debug Context Configuration** (`⌃⇧D` on macOS). The IDE compiles the file with debug info (`-g`, and `-std=c++17` for C++) into a temporary folder and runs it.
|
||
|
||
See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing) for the general workflow.
|
||
|
||
## Debugging
|
||
|
||
Debugging uses a DAP adapter. C and C++ configurations default to **lldb-dap**. To use another one, open the run configuration and change **Debug adapter**:
|
||
|
||
- **lldb-dap (C, C++, Swift)**: LLVM's adapter, the default. The IDE does not install it.
|
||
- **CodeLLDB (Rust, C, C++)**: the IDE can install it; if it is missing when you start debugging, a notification offers to install it.
|
||
- **GDB (C, C++)**: GDB's own DAP mode (`gdb -i dap`). It needs GDB 14 or newer; older versions are refused with a message.
|
||
|
||
**Attach to Process…** lists native processes too. It attaches with CodeLLDB when it is installed, otherwise with lldb-dap.
|
||
|
||
See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||
|
||
## Arduino
|
||
|
||
`.ino` sketches use the Arduino Language Server, which drives clangd with Arduino's generated compile context. The IDE does not install it: install Arduino IDE 2 (it includes the Arduino Language Server, Arduino CLI and clangd) and the board's core. OpenIDEA finds those tools on `PATH` or inside Arduino IDE 2.
|
||
|
||
To override the paths, set them in **Settings › Languages & Frameworks › Language Servers**, or set `languages.arduino.cli`, `languages.arduino.clangd`, `languages.arduino.languageServer` and `languages.arduino.cliConfig` in `settings.toml`. Set the board FQBN in `sketch.yaml` or `languages.arduino.fqbn`. Plain `.cpp` files next to a sketch are still served by clangd.
|
||
|
||
There are no upload or serial monitor actions for Arduino.
|
||
|
||
## Limitations
|
||
|
||
- C and C++ code intelligence is only as good as clangd's compile flags. Without a `compile_commands.json` or `compile_flags.txt`, expect false errors.
|
||
- The IDE does not generate a compilation database for Make, Meson or other build systems.
|
||
- Catch2 v2 (`catch.hpp`) and Boost.Test executables run as plain applications: their tests are not listed in a test tree.
|
||
- lldb-dap and GDB are not installed by the IDE.
|