Header Files → Packages
Organizing multi-file programs
Introduction
In this lesson, you'll learn about header files → packages in Go. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with organizing multi-file programs.
Go has its own approach to organizing multi-file programs, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
// mathutil/mathutil.go
package mathutil
// Exported (capital letter) — public
func Add(a, b int) int { return a + b }
func Multiply(a, b int) int { return a * b }
// Unexported (lowercase) — package-private
func helper() {}
// main.go
package main
import (
"fmt"
"github.com/user/myapp/mathutil"
)
func main() {
fmt.Println(mathutil.Add(2, 3))
fmt.Println(mathutil.Multiply(4, 5))
}Comparing to C
Here's how you might have written similar code in C:
/* mathutil.h */
#ifndef MATHUTIL_H
#define MATHUTIL_H
int add(int a, int b);
int multiply(int a, int b);
#endif
/* mathutil.c */
#include "mathutil.h"
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
/* main.c */
#include <stdio.h>
#include "mathutil.h"
int main() {
printf("%d\n", add(2, 3));
printf("%d\n", multiply(4, 5));
return 0;
}You may be used to different syntax or behavior.
No header files in Go — packages replace .h + .c
You may be used to different syntax or behavior.
Go exports by capitalization; C uses header declarations
You may be used to different syntax or behavior.
Go modules (go.mod) replace Makefiles for dependency management
You may be used to different syntax or behavior.
No include guards needed — Go's package system handles this
Step-by-Step Breakdown
1. No Header Files
Go packages replace C's .h + .c split. A Go package is a directory of .go files — all exported symbols are automatically available.
2. Export Control
C controls exports via header files. Go uses a simpler rule: capitalized names are exported (public), lowercase are package-private.
/* mathutil.h */
int add(int a, int b); /* declares what's public */func Add(a, b int) int { ... } // exported (capital)
func helper() {} // package-private3. go.mod vs Makefile
Go modules (go.mod) handle dependencies and versioning, replacing the role of Makefiles in C projects.
// go.mod
module github.com/user/myapp
go 1.21
require (
github.com/some/dep v1.2.3
)Common Mistakes
When coming from C, developers often make these mistakes:
- No header files in Go — packages replace .h + .c
- Go exports by capitalization; C uses header declarations
- Go modules (go.mod) replace Makefiles for dependency management
Key Takeaways
- No .h header files — packages combine declaration and implementation
- Exported names start with capital letters
- go.mod replaces Makefile for dependency management
- Go compiler handles all include ordering automatically