Skip to content
Skills Library
Programming · Automation

makefile-generator

/makefile-generator

Generate GNU Make build systems that define build targets, configure dependencies, set up phony targets, and implement parallel builds. Use when creating make/Makefile/.mk files, implementing compile rules, or building production-ready build automation for C/C++, Go, Python, and Java projects.

Repository
tekhne ↗
Licence
MIT
Last repository change
21.10.2026

Assessment and security

93/ 100Class: good
Format20 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene13 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
35
Scripts
2
HTML comments
0
URLs in SKILL.md
3
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What to check before installing
  • 2 scripts in this package. Review them before installing, as Claude may execute them.

Scripts: scripts/add_standard_targets.sh, scripts/generate_makefile_template.sh

What it does and when to use it

Generate GNU Make build systems that define build targets, configure dependencies, set up phony targets, and implement parallel builds. Use when creating make/Makefile/.mk files, implementing compile rules, or building production-ready build automation for C/C++, Go, Python, and Java projects.

Original author description

Generate GNU Make build systems that define build targets, configure dependencies, set up phony targets, and implement parallel builds. Use when creating make/Makefile/.mk files, implementing compile rules, or building production-ready build automation for C/C++, Go, Python, and Java projects.

How it works

  1. Overview
  2. Mindset
  3. When to Use
  4. When NOT to Use
  5. Generation Workflow
  6. Best Practices
  7. Documentation
  8. Anti-Patterns
  9. References
Original SKILL.md headings · 470 lines, 2,567 words
SKILL.md preview
---
name: makefile-generator
description: Generate GNU Make build systems that define build targets, configure dependencies, set up phony targets, and implement parallel builds. Use when creating make/Makefile/.mk files, implementing compile rules, or building production-ready build automation for C/C++, Go, Python, and Java projects.
---

# Makefile Generator

## Overview

Generate production-ready Makefiles with best practices for C/C++, Python, Go, Java, and generic projects. Features GNU Coding Standards compliance, standard targets, security hardening, and automatic validation via devops-skills:makefile-validator skill.

## Mindset

Treat every target as a promise about a file, not a label for a command. Make decides whether to run a recipe by comparing file timestamps, so a target that does not correspond to a real output file must always be declared `.PHONY`, or Make will silently skip it the day a file with that name happens to exist. Never write a recipe that depends on inherited shell state; each recipe line runs in its own subshell, so a `cd` or `export` on one line has no effect on the next unless `.ONESHELL` is set or the lines are joined with `\`. Always prefer an explicit rule over an implicit one for anything that matters to the build's correctness — implicit rules are pattern-matched and order-dependent, which makes a broken build far harder to diagnose than an explicit prerequisite list. Verify that recipes never assume an environment variable exists; recipe shells do not always inherit the invoking shell's exported variables, so anything the recipe needs must be declared as a Make variable instead.

## When to Use

- Creating new Makefiles from scratch
- Setting up build systems for projects (C/C++, Python, Go, Java)
- Implementing build automation and CI/CD integration
- Converting manual build processes to Makefiles
- The user asks to "create", "generate", or "write" a Makefile

## When NOT to Use

Do not use this skill for validating or linting an existing Makefile — that is the `makefile-validator` skill's job, not this one. Do not use it for debugging a build that is already failing (`make -d` and manual tracing are the right tool there), and do not use it as a substitute for actually running the build; generating a Makefile is not the same as verifying it builds successfully.

## Generation Workflow

### Stage 1: Gather Requirements

Collect information for the following categories. **Use AskUserQuestion when information is missing or ambiguous:**

| Category | Information Needed |
|----------|-------------------|
| **Project** | Language (C/C++/Python/Go/Java), structure (single/multi-directory) |
| **Build** | Source files, output artifacts, dependencies, build order |
| **Install** | PREFIX location, directories (bin/lib/share), files to install |
| **Targets** | all, install, clean, test, dist, help (which are needed?) |
| **Config** | Compiler, flags, pkg-config dependencies, cross-compilation |

**When to Use AskUserQuestion:** MUST ask when language unspecified, project structure unclear, Docker registry unknown, multiple binaries possible, install paths unclear, or cross-compilation mentioned. Example questions: "What programming language?", "Single or multi-directory project?", "Which container registry?", "Target platform/architecture?"

**Skip when:** User provides all info explicitly, standard project with obvious defaults (e.g., "Go project with Docker"), or user says "use defaults".

**Default Assumptions:** Single-directory, PREFIX=/usr/local, standard targets (all/build/test/clean/install/help), no cross-compilation.

### Stage 2: Documentation Lookup

**When REQUIRED (MUST perform lookup):**
- User requests integration with unfamiliar tools, frameworks, or build systems
- Complex build patterns not covered in Stage 3 examples (e.g., Bazel, Meson, custom toolchains)
- **Docker/container integration** (Dockerfile builds, multi-stage, registry push)
- CI/CD platform-specific integration (GitHub Actions, GitLab CI, Jenkins)
- Cross-compilation for unusual targets or embedded systems
- Package manager integration (Conan, vcpkg, Homebrew formulas)
- **Multi-binary or multi-library projects**
- **Version embedding via ldflags or build-time variables**

**When OPTIONAL (may skip external lookup):**
- Standard language patterns already covered in Stage 3 (C/C++, Go, Python, Java)
- Simple single-binary projects with no external dependencies
- User provides complete requirements with no ambiguity
- Internal docs already cover the required pattern comprehensively

**Lookup Process (follow in order):**

1. **ALWAYS consult internal references/ FIRST using the Read tool** (primary source of truth):

   | Requirement | Read This Doc |
   |-------------|---------------|
   | Docker/container targets | `references/patterns-guide.md` (Pattern 8: Docker Integration) |
   | Multi-binary projects | `references/patterns-guide.md` (Pattern 7: Multi-Binary Project) |
   | Go projects with version embedding | `references/patterns-guide.md` (Pattern 5: Go Project) |
   | Parallel builds, caching, ccache | `references/optimization-guide.md` |
   | Credentials, secrets, API keys | `references/security-guide.md` |
   | Complex dependencies, pattern rules | `references/patterns-guide.md` |
   | Order-only prerequisites | `references/optimization-guide.md` or `references/targets-guide.md` |
   | Variables, assignment operators | `references/variables-guide.md` |

   **CRITICAL:** You MUST explicitly use the Read tool to consult relevant docs during generation, even if you have prior knowledge. Do NOT rely on context from earlier in the conversation. This ensures patterns are always current and correctly applied.

   **Required Workflow Example (Docker + Go with version embedding):**
   ```
   # Step 1: Use Read tool to get Go pattern
   Read: references/patterns-guide.md (find Pattern 5: Go Project)

   # Step 2: Use Read tool to get Docker pattern
   Read: references/patterns-guide.md (find Pattern 8: Docker Integration)

   # Step 3: Use Read tool for security considerations
   Read: references/security-guide.md (credential handling for docker-push)

   # Step 4: Generate Makefile combining patterns
   # Step 5: Document which docs were consulted in Makefile header
   ```

   **Important:** Internal docs contain vetted, production-ready patterns. Always read the relevant docs before external lookups.

2. **Try context7 for external tool documentation** (when internal docs don't cover a specific tool):
   ```
   # Only needed for tools/frameworks NOT covered in internal docs
   mcp__context7__resolve-library-id: "<tool-name>"
   mcp__context7__get-library-docs: topic="<integration-topic>"

   # Example topics:
   # - For Docker: topic="dockerfile best practices"
   # - For Go: topic="go build ldflags"
   # - For specific tools: topic="<tool> makefile integration"
   ```
   **Note:** Context7 may not have GNU Make-specific documentation. Skip if internal docs provide sufficient patterns.

3. **Fallback to WebSearch** (only if pattern not found in internal docs OR context7):
   ```
   "<specific-feature>" makefile best practices 2025
   Example: "docker makefile best practices 2025"
   Example: "go ldflags version makefile 2025"
   ```
   **Trigger WebSearch when:** Internal docs don't cover the specific integration AND context7 returns no relevant results.

**Note:** Document which internal docs you consulted in your response (add comment in generated Makefile header).

### Stage 3: Generate Makefile

#### Header (choose one style)

**Traditional (POSIX-compatible):**
```makefile
.DELETE_ON_ERROR:
.SUFFIXES:
```

**Modern (GNU Make 4.0+, recommended):**
```makefile
SHELL := bash
.ONESHELL:
.SHELLFLAGS := -eu -o pipefail -c
.DELETE_ON_ERROR:
.SUFFIXES:
MAKEFLAGS += --warn-undefined-variables
MAKEFLAGS += --no-builtin-rules
```

#### Standard Variables

```makefile
# User-overridable (use ?=)
CC ?= gcc
CFLAGS ?= -Wall -Wextra -O2
PREFIX ?= /usr/local
DESTDIR ?=

# GNU installation directories
BINDIR ?= $(PREFIX)/bin
LIBDIR ?= $(PREFIX)/lib
INCLUDEDIR ?= $(PREFIX)/include

# Project-specific (use :=)
PROJECT := myproject
VERSION := 1.0.0
SRCDIR := src
BUILDDIR := build
SOURCES := $(wildcard $(SRCDIR)/*.c)
OBJECTS := $(SOURCES:$(SRCDIR)/%.c=$(BUILDDIR)/%.o)
```

#### Language-Specific Build Rules

**C/C++:**
```makefile
$(TARGET): $(OBJECTS)
	$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@

$(BUILDDIR)/%.o: $(SRCDIR)/%.c
	@mkdir -p $(@D)
	$(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c $< -o $@

-include $(OBJECTS:.o=.d)
```

**Go:**
```makefile
$(TARGET): $(shell find . -name '*.go') go.mod
	go build -o $@ ./cmd/$(PROJECT)
```

**Python:**
```makefile
.PHONY: build
build:
	python -m build

.PHONY: develop
develop:
	pip install -e .[dev]
```

**Java:**
```makefile
$(BUILDDIR)/%.class: $(SRCDIR)/%.java
	@mkdir -p $(@D)
	javac -d $(BUILDDIR) -sourcepath $(SRCDIR) $<
```

#### Standard Targets

```makefile
.PHONY: all clean install uninstall test help

## Build all targets
all: $(TARGET)

## Install to PREFIX
install: all
	install -d $(DESTDIR)$(BINDIR)
	install -m 755 $(TARGET) $(DESTDIR)$(BINDIR)/

## Remove built files
clean:
	$(RM) -r $(BUILDDIR) $(TARGET)

## Run tests
test:
	# Add test commands

## Show help
help:
	@echo "$(PROJECT) v$(VERSION)"
	@echo "Targets: all, install, clean, test, help"
	@echo "Override: make CC=clang PREFIX=/opt"
```

### Stage 4: Validate and Format

**CRITICAL: Always validate using devops-skills:makefile-validator skill.**

```
1. Generate Makefile following stages above
2. Invoke devops-skills:makefile-validator skill
3. Fix any errors identified (MUST have 0 errors)
4. Apply formatting fixes (see "Formatting Step" below)
5. Fix warnings (SHOULD fix; explain if skipped)
6. Address info items for large/production projects
7. Re-validate until checks pass
8. Output structured validation report (REQUIRED - see format below)
```

#### Formatting Step (REQUIRED)

When mbake reports formatting issues, you MUST either:

1. **Auto-apply formatting** (preferred for minor issues):
   ```bash
   mbake format <Makefile>
   ```

2. **Explain why not applied** (if formatting would break functionality):
   ```
   Formatting not applied because:
   - [specific reason, e.g., "heredoc syntax would be corrupted"]
   - Manual review recommended for: [specific lines]
   ```

**Formatting Decision Guide:**

| mbake Report | Action |
|--------------|--------|
| "Would reformat" with no specific issues | Auto-apply with `mbake format` |
| Specific whitespace/indentation issues | Auto-apply with `mbake format` |
| Issues in complex heredocs or multi-line strings | Skip formatting, explain in output |
| Issues in `# bake-format off` sections | Skip (intentionally disabled) |

**Validation Pass Criteria:**

| Level | Requirement | Action |
|-------|-------------|--------|
| **Errors (0 required)** | Syntax errors, missing tabs, invalid targets | MUST fix before completion |
| **Warnings (fix if feasible)** | Formatting issues, missing optimizations | SHOULD fix; explain if skipped |
| **Info (address for production)** | Enhancement suggestions, style preferences | SHOULD address for production Makefiles |

**Known mbake False Positives (can be safely ignored):**

The mbake validator may report warnings for valid GNU Make special targets. These are false positives and can be ignored:

| mbake Warning | Actual Status | Explanation |
|---------------|---------------|-------------|
| "Unknown special target '.DELETE_ON_ERROR'" | ✅ Valid | Critical GNU Make target that deletes failed build artifacts |
| "Unknown special target '.SUFFIXES'" | ✅ Valid | Standard GNU Make target for disabling/setting suffix rules |
| "Unknown special target '.ONESHELL'" | ✅ Valid | GNU Make 3.82+ feature for single-shell recipe execution |
| "Unknown special target '.POSIX'" | ✅ Valid | POSIX compliance declaration |

#### Validation Report Output (REQUIRED)

After validation completes, output a structured report with: **Result** (PASSED/FAILED), **Errors/Warnings/Info counts**, **Changes applied** (errors fixed, warnings addressed, formatting applied), and **Remaining issues**.

**Common Info Items to Address:**

| Info Item | When to Fix | How to Fix |
|-----------|-------------|------------|
| "mkdir without order-only prerequisites" | Large projects (>10 targets) | Use `target: prereqs \| $(BUILDDIR)` pattern |
| "recipe commands lack error handling" | Critical operations (install, deploy) | Add `set -e` in .SHELLFLAGS or use `&&` chaining |
| "consider using ccache" | Long compile times | Add `CC := ccache $(CC)` pattern |
| "parallel-sensitive commands detected" | Docker/npm/pip targets | Add `.NOTPARALLEL:` for affected targets or proper dependencies |

**Production-Quality Requirements (MUST address for Docker/deploy targets):**

When generating Makefiles with Docker or deployment targets, you MUST apply these production patterns:

1. **Error Handling for docker-push:**
   ```makefile
   ## Push Docker image to registry (with error handling)
   docker-push: docker-build
   	@echo "Pushing $(IMAGE)..."
   	docker push $(IMAGE) || { echo "Failed to push $(IMAGE)"; exit 1; }
   	docker push $(IMAGE_LATEST) || { echo "Failed to push $(IMAGE_LATEST)"; exit 1; }
   ```

2. **Parallel Safety for Docker targets:**
   ```makefile
   # Prevent parallel execution of Docker targets (race conditions)
   .NOTPARALLEL: docker-build docker-push docker-run
   ```
   Or use proper dependencies to serialize:
   ```makefile
   docker-push: docker-build  # Ensures build completes before push
   docker-run: docker-build   # Ensures build completes before run
   ```

3. **Install target error handling:**
   ```makefile
   install: $(TARGET)
   	install -d $(DESTDIR)$(PREFIX)/bin || exit 1
   	install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin/ || exit 1
   ```

**Note:** When validation shows info items about error handling or parallel safety, you MUST address them for any Makefile containing Docker, deploy, or install targets. Explain in your response which patterns were applied.

**Validation Checklist:**
- [ ] Syntax correct (`make -n` passes)
- [ ] All non-file targets have .PHONY
- [ ] Tab indentation (not spaces)
- [ ] No hardcoded credentials
- [ ] User-overridable variables use `?=`
- [ ] .DELETE_ON_ERROR present
- [ ] MAKEFLAGS optimizations included (Modern header)
- [ ] Order-only prerequisites for build directories (large projects)
- [ ] Error handling in critical recipes (install, deploy, docker-push)

## Best Practices

### Variables
- `?=` for user-overridable (CC, CFLAGS, PREFIX)
- `:=` for project-specific (SOURCES, OBJECTS)
- Use pkg-config: `CFLAGS += $(shell pkg-config --cflags lib)`

### Targets
- Always declare `.PHONY` for non-file targets
- Default target should be `all`
- Use `.DELETE_ON_ERROR` for safety
- Document with `##` comments for help target

### Directory Creation
Two approaches for creating build directories:

**Simple (inline mkdir):**
```makefile
$(BUILDDIR)/%.o: $(SRCDIR)/%.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) -c $< -o $@
```

**Optimized (order-only prerequisites):** Prevents unnecessary rebuilds when directory timestamps change.
```makefile
$(BUILDDIR):
	@mkdir -p $@

$(BUILDDIR)/%.o: $(SRCDIR)/%.c | $(BUILDDIR)
	$(CC) $(CFLAGS) -c $< -o $@
```
Use order-only prerequisites (`|`) for large projects with many targets.

### Recipes
- Use tabs, never spaces
- Quote variables in shell: `$(RM) "$(TARGET)"`
- Use `@` prefix for quiet commands
- Test with `make -n` first

## Documentation

Detailed guides in `references/`:
- **makefile-structure.md** - Organization, layout, includes
- **variables-guide.md** - Assignment operators, automatic variables
- **targets-guide.md** - Standard targets, .PHONY, prerequisites
- **patterns-guide.md** - Pattern rules, dependencies
- **optimization-guide.md** - Parallel builds, caching
- **security-guide.md** - Safe expansion, credential handling

## Anti-Patterns

### NEVER declare phony targets without `.PHONY`

- **WHY:** If a file named `clean` or `test` exists in the directory, Make treats the target as up-to-date and silently skips it.
- **BAD**: `clean:\n\trm -rf dist/` without `.PHONY: clean`
- **GOOD**: Declare all non-file targets in `.PHONY: clean test build install` at the top of the Makefile.

### NEVER use `make` recursively instead of `$(MAKE)`

- **WHY:** Bare `make` in a recipe does not inherit the parent's `-j` jobserver, `-n` dry-run, or `-k` keep-going flags, causing inconsistent behavior in parallel and CI builds.
- **BAD**: `dist:\n\tmake -C subdir all`
- **GOOD**: `dist:\n\t$(MAKE) -C subdir all`

### NEVER rely on shell environment variables in recipes without declaring them as Make variables

- **WHY:** Recipe shells are non-interactive and may not inherit all environment variables; undeclared variables expand to empty strings silently.
- **BAD**: `deploy:\n\techo "Deploying to $$ENVIRONMENT"` expecting `ENVIRONMENT` from the shell environment without a fallback.
- **GOOD**: Declare `ENVIRONMENT ?= staging` at the top, then use `$(ENVIRONMENT)` in recipes.

### NEVER use implicit rules for critical build targets

- **WHY:** Implicit rules are order-dependent and hard to debug; explicit rules make the build graph transparent and reproducible.
- **BAD**: Relying on the built-in `%.o: %.c` implicit rule without declaring it explicitly for project sources.
- **GOOD**: Define explicit pattern rules or list all build targets explicitly.

### NEVER put multi-line logic in recipe shells without `.ONESHELL` or explicit line continuations

- **WHY:** Each recipe line runs in a separate shell; `cd` in one line does not affect the next.
- **BAD**: `deploy:\n\tcd dist\n\tnpm publish` (`cd` has no effect on the second line).
- **GOOD**: Chain commands with `&&` in a single line: `cd dist && npm publish`, or add `.ONESHELL:` at the top.

## References

These scripts are **optional convenience tools** for quick template generation.

### When to Use Scripts vs Manual Generation

Use `scripts/generate_makefile_template.sh` for simple standard projects. Use manual generation for complex projects (Docker, multi-binary, custom patterns) or specific user requirements.

### generate_makefile_template.sh

Generates a complete Makefile template for a specific project type.

```bash
bash scripts/generate_makefile_template.sh [TYPE] [NAME]

Types: c, c-lib, cpp, go, python, java, generic
```

**Example:**
```bash
bash scripts/generate_makefile_template.sh go myservice
# Creates Makefile with Go patterns, version embedding, standard targets
```

### add_standard_targets.sh

Adds missing standard GNU targets to an existing Makefile.

```bash
bash scripts/add_standard_targets.sh [MAKEFILE] [TARGETS...]

Targets: all, install, uninstall, clean, distclean, test, check, help
```

**Example:**
```bash
bash scripts/add_standard_targets.sh Makefile install uninstall help
# Adds install, uninstall, help targets if they don't exist
```

**Note:** Manual generation following the Stage 3 patterns produces equivalent results but allows for more customization.
- [GNU Make Manual](https://www.gnu.org/software/make/manual/)
- [GNU Coding Standards](https://www.gnu.org/prep/standards/standards.html)
- [Makefile Conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html)
Files in this package (35)
  • SKILL.md 19 KB
  • .audits/latest 1 KB
  • .audits/2026-03-02/analysis.md 1 KB
  • .audits/2026-03-02/audit.json 1 KB
  • .audits/2026-03-02/remediation-plan.md 2 KB
  • .audits/2026-09-23/Analysis.md 1 KB
  • .audits/2026-09-23/Remediation.md 1 KB
  • .audits/2026-09-23/audit.json 1 KB
  • assets/templates/.gitkeep 1 KB
  • evals/instructions.json 4 KB
  • evals/summary.json 1 KB
  • evals/scenario-0/capability.txt 1 KB
  • evals/scenario-0/criteria.json 2 KB
  • evals/scenario-0/task.md 1 KB
  • evals/scenario-1/capability.txt 1 KB
  • evals/scenario-1/criteria.json 1 KB
  • evals/scenario-1/task.md 1 KB
  • evals/scenario-2/capability.txt 1 KB
  • evals/scenario-2/criteria.json 1 KB
  • evals/scenario-2/task.md 1 KB
  • evals/scenario-3/capability.txt 1 KB
  • evals/scenario-3/criteria.json 2 KB
  • evals/scenario-3/task.md 1 KB
  • evals/scenario-4/capability.txt 1 KB
  • evals/scenario-4/criteria.json 1 KB
  • evals/scenario-4/task.md 1 KB
  • references/README.md 2 KB
  • references/makefile-structure.md 11 KB
  • references/optimization-guide.md 16 KB
  • references/patterns-guide.md 12 KB
  • references/security-guide.md 8 KB
  • references/targets-guide.md 13 KB
  • references/variables-guide.md 13 KB
  • scripts/add_standard_targets.sh 10 KB
  • scripts/generate_makefile_template.sh 13 KB

Versions

RepositoryScoreLicence
This page · pantheon-org/tekhne93MIT
jeremylongshore/tons-of-skills-marketplace100MIT
VladButacu/agentkit100MIT

Database snapshot: 13.11.2026 · package version 863d76d16450 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 3 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95makefile
    GNU Make automation and build system guidance. Use when creating or maintaining Makefiles, writing Make targets and recipes, or configuring GNU Make build automation. Keywords: Makefile, GNU Make, targets, recipes, build automation.
  • 100makefile-pro
    Generate, scaffold, validate and lint Makefiles and .mk files: .PHONY targets, build automation, common mistakes. Use for any Makefile work.
  • 100makefile
    Best practices for authoring GNU Make Makefiles Triggers on: **/Makefile, **/makefile, **/*.mk, **/GNUmakefile
  • 100configure-makefile
    Makefile with standard targets (help, test, build, clean, lint). Use when setting up a Makefile, auditing missing targets, or adding language-specific targets.
  • 95make
    Use when writing or debugging Makefiles, understanding pattern rules and automatic dependency generation, managing CFLAGS/LDFLAGS, or diagnosing incremental build, phony targets, or recursive make.
  • 90makefile-design
    Write Makefiles with honest dependencies, phony discipline, and self-documenting help, and know when make is the wrong tool. Use when standardizing project task-running or fixing rebuild bugs.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.