Unlock efficient C++ coding in Cursor with these detailed rules covering modern standards, CMake, testing, CI/CD, and more. Elevate your projects from setup to deployment.
## Why Follow Specific Rules for C++ Development in Cursor?
Developing C++ applications demands precision, especially in an AI-assisted editor like Cursor. These guidelines ensure your code is modern, maintainable, and performant. Cursor's AI can enforce these rules dynamically, suggesting fixes and generating boilerplate. By adhering to them, you reduce bugs, speed up collaboration, and prepare for production. Let's explore each area through key questions and actionable strategies.
## What Modern C++ Features Should You Prioritize?
Always target C++20 or later as the baseline standard. This unlocks powerful features like concepts, ranges, coroutines, and modules, minimizing legacy pitfalls.
- **Prefer RAII over manual resource management**: Use `std::unique_ptr` and `std::shared_ptr` instead of raw pointers to prevent leaks.
- **Leverage `std::optional` and `std::expected`**: Handle absent or erroneous values gracefully without nulls.
- **Embrace `constexpr` and `constinit`**: Compile-time evaluation boosts performance and safety.
**Example**:
```cpp
#include <memory>
#include <optional>
class Resource {
public:
Resource() { /* acquire */ }
~Resource() { /* release */ }
};
std::unique_ptr<Resource> createResource() {
return std::make_unique<Resource>();
}
std::optional<int> safeDivide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
```
This approach scales to large projects, where Cursor can autocomplete these idioms seamlessly.
## How Do You Enforce Consistent Code Style?
Consistency is key for team readability. Integrate `clang-format` with LLVM style as default, customized for C++.
**Recommended `.clang-format` snippet**:
```yaml
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
AccessModifierOffset: -4
```
Run `clang-format -i *.cpp *.h` pre-commit. Cursor's AI can format on save and highlight deviations. Why LLVM? It balances readability with brevity, aligning with most open-source C++ repos.
**Pro Tip**: Pair with `clang-tidy` for linting: `clang-tidy -checks='modernize-*,performance-*' file.cpp`.
## What's the Best Way to Structure CMake Builds?
Use CMake 3.20+ for declarative, target-centric builds. Avoid `make_directory` or `add_subdirectory` hacks.
**Core Practices**:
- Generate compile_commands.json: `set(CMAKE_EXPORT_COMPILE_COMMANDS ON)`.
- FetchContent for dependencies.
- Target-based linking: `target_link_libraries(my_target PRIVATE some_lib)`.
**Example CMakeLists.txt**:
```cmake
cmake_minimum_required(VERSION 3.20)
project(MyProject LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent)
FetchContent_Declare(
some_lib
GIT_REPOSITORY https://github.com/example/lib
)
FetchContent_MakeAvailable(some_lib)
add_executable(my_app main.cpp)
target_link_libraries(my_app PRIVATE some_lib)
```
Cursor excels here—prompt it with "Generate CMake for a C++20 app with threading" for instant setups. This modular structure supports multi-platform builds effortlessly.
## How Should You Manage External Dependencies?
Opt for declarative managers to avoid vendoring. Primary recommendation: [vcpkg](https://github.com/Microsoft/vcpkg), Microsoft's cross-platform tool.
**Integration**:
```powershell
vcpkg install fmt range-v3
vcpkg integrate install # Links to VS/MSBuild/CMake
```
In CMake: `find_package(fmt CONFIG REQUIRED)`.
**Alternative**: Conan for fine-grained control. Cursor can generate vcpkg manifests or conanfile.py from natural language descriptions, streamlining onboarding.
Real-world: For a networking app, `vcpkg install boost-asio` ensures reproducible builds across Windows/Linux/macOS.
## How to Implement Robust Testing?
Unit tests are non-negotiable. Use [Catch2](https://github.com/catchorg/Catch2) for simplicity or GoogleTest for scale.
**Catch2 Example**:
```cpp
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
TEST_CASE("Basic math", "[math]") {
REQUIRE(1 + 1 == 2);
}
```
Aim for 80%+ coverage. Integrate via CMake: `FetchContent_Declare(Catch2 ...)`.
**Benchmarking**: Use [Google Benchmark](https://github.com/google/benchmark) for perf regression.
```cpp
#include <benchmark/benchmark.h>
static void BM_Sort(benchmark::State& state) {
std::vector<int> v(1000); /* fill */
for (auto _ : state) {
std::sort(v.begin(), v.end());
}
}
BENCHMARK(BM_Sort);
```
Cursor's diff previews make test-driven development (TDD) intuitive—generate tests from specs.
## Best Practices for Concurrency and Performance?
Favor `std::jthread`, `std::stop_token` (C++20). Use `std::execution::par` for parallelism.
Profile with sanitizers: `-fsanitize=address,undefined`. For CPU: perf or VTune.
**Ranges over Loops**:
```cpp
#include <ranges>
auto even_squares = nums
| std::views::filter([](int i){ return i % 2 == 0; })
| std::views::transform([](int i){ return i * i; });
```
This declarative style reduces errors; Cursor suggests range pipelines automatically.
## How to Debug Effectively?
Enable sanitizers in Debug builds:
```cmake
target_compile_options(my_target PRIVATE -fsanitize=address,undefined -g)
```
Use GDB/LLDB with Cursor's integrated debugger. Valgrind for leaks. Log with spdlog, levels: trace/debug/info.
## Git Workflow and Version Control Tips
Branch per feature: `git checkout -b feature/x`. Commit atomically: "feat: add user auth".
`.gitignore`: Ignore build/, .vscode/, compile_commands.json.
Pre-commit hooks for format/lint.
## Setting Up CI/CD with GitHub Actions
Automate builds/tests. **Workflow Example**:
```yaml
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: microsoft/vcpkg@v1 # Cache vcpkg
- run: cmake --build build/ -j
- run: ctest -V
```
Matrix for compilers: GCC/Clang/MSVC. Cursor generates these YAMLs from prompts.
## Containerization with Docker
Dockerize for consistency:
```dockerfile
FROM gcc:13
WORKDIR /app
COPY . .
RUN cmake -B build && cmake --build build
CMD ["./build/my_app"]
```
Multi-stage for slim images. Devcontainers (.devcontainer/devcontainer.json) integrate with Cursor/VSCode.
## Documentation and Doxygen
/** Javadoc-style */ comments. CMake: `find_package(Doxygen)`.
Generate with `doxygen Doxyfile`.
## Security Considerations
Static analysis: CodeQL in CI. Avoid `strcpy`; use `std::string`. Cryptography: libsodium.
## Diving into Advanced C++ Topics
- **Modules**: `export module mylib;` replacing headers.
- **Coroutines**: `task<int> asyncOp() { co_await ...; }
- **Concepts**: `template<Regular T> void func(T t);`
Cursor shines in generating module migrations or coroutine flows.
## Final Thoughts: Integrating These Rules in Cursor
Paste these as Cursor Rules for AI adherence. Prompt: "Refactor to C++20 RAII". Track with `.cursor/rules.md`. This workflow transforms Cursor into a C++ expert companion, from solo hacks to enterprise apps.
<div style="text-align: center; margin-top: 2rem;">
<a href="https://cursor.directory/c++-development-cursor-rules" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a>
</div>