OpenBSD GCC Compiler - Beginner Guide
| OpenBSD GCC Compiler - Beginner Guide | |
| Step 1: Install GCC | |
| Step 2: Your First C Program | |
| Step 3: Compiling with Warnings and Debugging | |
| Step 4: Compiling C++ Programs | |
| Step 5: Making a Makefile |
OpenBSD GCC Compiler - Beginner Guide
The GCC (GNU Compiler Collection) is essential for compiling C and other programs. Here's how to install and use it on OpenBSD.
Step 1: Install GCC
OpenBSD uses the pkg_add command to install software.
pkg_add gcc - installs the GCC compiler collection
What you get: The GCC compiler, assembler, and related tools for compiling C, C++, and other languages.
After installation: Verify it worked:
gcc --version - should display version information (e.g., gcc (OpenBSD) 11.4.0)
Step 2: Your First C Program
Let's compile a simple "Hello, World!" program.
Create the source file:
vi hello.c
Press i to insert, type the following, press Esc, then type :wq and press Enter:
#includeint main() { printf("Hello, OpenBSD World!\n"); return 0; }
Compile the program:
gcc hello.c -o helloWhat this does:
gcc - the compilerhello.c - your source file name-o hello - name the output file hello (instead of the default a.out)Run your program:
./helloYou should see:
Hello, OpenBSD World! displayed in the terminal.
Step 3: Compiling with Warnings and Debugging
For better code quality, use these useful flags:
-Wall: Show all common warnings
-Wextra: Show extra warnings beyond Wall
-g: Include debugging information (allows using gdb debugger)
Example command:
gcc -Wall -Wextra -g hello.c -o hello
This will:
- Warn about potential issues in your code
- Add debugging symbols so you can trace through the program later
- Help you write more robust code
Step 4: Compiling C++ Programs
To compile C++ programs, use g++ (which is installed with gcc):
g++ hello.cpp -o hello
Or with warnings:
g++ -Wall -Wextra -g hello.cpp -o hello
C++ specifics: C++ has more compiler warnings than C due to its complexity.
Pay attention to warnings about deprecated functions, unused variables, etc.
Step 5: Making a Makefile
For larger projects, use a Makefile to automate compilation.
Create a Makefile:
vi Makefile
Type the following, press Esc, then type :wq and press Enter:
CC = gcc
CFLAGS = -Wall -Wextra -g
all: hello
hello: hello.c
$(CC) $(CFLAGS) -o hello hello.c
clean:
rm -f hello
Now compile: Simply type:
make - compiles your program using the MakefileTo clean up:
make clean - removes the compiled files
Ready for more development tools? Proceed to Lesson 62: Make Build System.
Next: OpenBSD Virtual Machines - Beginner Guide
Article author: Arthur Isaev