Here's a guide on using g++ on the command line:
1. Accessing the Command Line:
- Windows: Open Command Prompt or PowerShell.
- Linux/macOS: Open Terminal.
2. Checking g++ Availability:
- Type
g++ --version
and press Enter. If installed, it'll display the version. If not, install it using your system's package manager.
3. Basic Compilation:
- Navigate to the directory containing your C++ source file(s) using the
cd
command. - Compile a single file:
g++ filename.cpp -o output_filename
- Replace
filename.cpp
with your actual file name. - The
-o
flag specifies the output file name.
- Replace
4. Compiling Multiple Files:
g++ file1.cpp file2.cpp -o output_filename
- List all files to be compiled, separated by spaces.
5. Common Options:
- -Wall: Enables most warnings to help you catch potential errors.
- -g: Includes debugging information for using a debugger.
- -std=c++#: Specifies the C++ language standard to use (e.g.,
-std=c++17
).
6. Linking Libraries:
- Pass library names after your source files, prefixed with
-l
:g++ main.cpp -o myprogram -lm -lpthread
7. Including Header Files from Non-Standard Locations:
- Use the
-I
flag to specify additional header file search paths:g++ main.cpp -o myprogram -I/path/to/headers
8. Running the Executable:
- Once compiled successfully, run the executable:
./output_filename
Additional Tips:
- Use
-c
to create object files (.o
) without linking. - Use
make
for managing complex projects with multiple files and dependencies. - Consult g++'s online documentation for more advanced options and features.