How to create a nix shell for C++ programming

I seem to have installed everything for C++, but lsp still doesn’t see the header files for some reason.

Define “installed”. If you put it in your config, remove it.
If you made a shell.nix or some mkShell environment, share that code.

My flake.nix:

{
  description = "C++ dev";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
  };

  outputs = { self, nixpkgs }:
    let
      system = "x86_64-linux";
      pkgs = nixpkgs.legacyPackages.${system};
    in
    {
      devShells.${system}.default = pkgs.mkShell.override {
      } {
        packages = with pkgs; [
          cmake
          ninja
          pkg-config
          clang
          lld
          lldb
          clang-tools
        ];

        shellHook = ''
          echo "C++ dev environment"
          clang++ --version
        '';
      };
    };
}
{
  description = "C++ dev";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
  };

  outputs = { self, nixpkgs }:
    let
      system = "x86_64-linux";
      pkgs = nixpkgs.legacyPackages.${system};
    in
    {
      devShells.${system}.default = pkgs.mkShell.override {
        stdenv = pkgs.clang19Stdenv;
      } {
        packages = with pkgs; [
          cmake
        ];
        shellHook = ''
          echo "C++ dev environment"
        '';
      };
    };
}

Still not working

What exactly does “not working” mean?

The program is now being compiled, but the code editors (I tried in helix and zed-editor) show the error 'iostream' file not found (clang pp_file_not_found)

Do you have a compile_commands.json?

No, but how do I create it? (sorry, I’m just a newbie and I haven’t figured it out yet)

Hi there,
I use Zed Editor with C++ too and ran into the same issue with header files. I found a workaround in some discussions and while it’s definitely not ideal - it’s a nice temporary fix, at least for me, who still learning NixOS :sweat_smile:.

In your CMakeLists.txt, add this:

set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE INTERNAL "")
if(CMAKE_EXPORT_COMPILE_COMMANDS)
    set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
      ${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES})
endif()

Then, run:

cmake -S . -B build/
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1
2 Likes

Sorry to come back here after all this time, but I’ve already gone through everything, and it doesn’t help, the editors don’t see the header files.

Have you opened the editors AFER you cd to the directory and opend them from the command line there?

I open the editor on the command line in nix-shell