VSCode Doesn't Detect g++: Unable to Run C/C++ File on Linux
If you're using NixOS and trying to compile a C/C++ file in Visual Studio Code (VSCode) but receiving an error that g++ is not detected, this article will guide you through the process of resolving the issue. Although this tutorial is focused on NixOS, the steps should be similar for other Linux distributions.
Ensure g++ is Installed
First, let's confirm that g++ is installed on your system. Open a terminal and run the following command:
g++ --version
If g++ is installed, you should see output similar to:
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
If you receive an error that g++ is not installed, you will need to install it. On NixOS, you can use the following command:
nix-env -i gcc g++
Configure VSCode to Use g++
After ensuring that g++ is installed, you will need to configure VSCode to use it. First, open your C/C++ file in VSCode. Next, open the Command Palette by pressing Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac). Type "Tasks" and select "Tasks: Open User Tasks". If a "tasks.json" file does not exist, create one in the .vscode directory in your workspace.
Add the following code to your "tasks.json" file:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
This configuration tells VSCode to use g++ to build your C/C++ files. The "-g" flag tells g++ to include debug information, which can be helpful for debugging your code. The "${file}" variable is replaced with the name of the currently active file, and the "-o" flag specifies the output file name.
Test Your Configuration
To test your configuration, create a simple C/C++ file, such as the following:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
Save the file and open the Command Palette. Type "Tasks" and select "Run Build Task". If your configuration is correct, you should see output similar to the following:
/tmp/main
You can now run your program by opening a terminal in VSCode and running the following command:
./main
You should see the output "Hello, world!".
- Confirm that g++ is installed on your system.
- Configure VSCode to use g++ by creating a "tasks.json" file in the .vscode directory in your workspace.
- Test your configuration by creating a simple C/C++ file and running the "Run Build Task" command in VSCode.