Technology
How to Run .cpp Code on Ubuntu
How to Run .cpp Code on Ubuntu
Running C code on Ubuntu is a common task for developers working with C programs. This guide will walk you through the steps to compile and run C code on Ubuntu using the terminal and a text editor. Whether you are a beginner or a seasoned developer, this guide will provide you with a comprehensive step-by-step process to get your C programs up and running.
Step-by-Step Guide to Running C Code on Ubuntu
1. Install a C Compiler
The first step is to install a C compiler, which in most cases will be the GNU Compiler Collection (GCC). You can usually find GCC pre-installed on Ubuntu; however, if it is not, you can install it using the terminal.
sudo apt update sudo apt install g
2. Write Your C Code
You can use any text editor to write your C code. Some popular text editors for Ubuntu include Vim, Emacs, and Nano. For this example, we will use Nano to write a simple "Hello, World!" program.
#include iostream using namespace std; int main() { std::cout "Hello, World!" endl; return 0; }
To create the file using Nano, open the terminal and type:
nano hello.cpp
Add the code above to the file, then save and exit by pressing CTRL X, followed by Y, and finally Enter.
3. Compile the C Code
Once your C code is written and saved, you can compile it using the C compiler. Use the following command in the terminal:
g hello.cpp -o hello
This command will compile your code and create an executable file named hello in the current directory.
4. Run the Executable
To run the compiled program, simply type the following command in the terminal:
./hello
This will run your C program and output "Hello, World!" to the terminal.
Summary of Commands
Here’s a quick summary of the commands:
sudo apt update sudo apt install g nano hello.cpp Write your C code g hello.cpp -o hello Compile the code ./hello Run the executable
Additional Notes
If you encounter any errors during the compilation process, check the error messages for guidance. They will often provide information about syntax errors or other issues with your code. Alternatively, you can use Integrated Development Environments (IDEs) like Code::Blocks, CLion, or Visual Studio Code with C extensions for a more user-friendly development environment. These tools often provide better syntax highlighting, debugging features, and project management capabilities.