Home >Backend Development >C++ >How to Create a Simple C Makefile?

How to Create a Simple C Makefile?

DDD
DDDOriginal
2024-12-04 16:17:15665browse

How to Create a Simple C   Makefile?

How to Make a SIMPLE C Makefile

This guide will walk you through the process of creating a simple Makefile for a C project. We will cover basic tasks such as compiling source files, linking objects, and creating executables.

Understanding Makefiles

A Makefile is a text file that specifies the dependencies between files in your project and the commands to build those files. Make uses these dependencies to determine which files need to be rebuilt when a source file changes.

Common Make Variables

Here are some common Make variables that you may find useful:

  • CC: The C compiler
  • CXX: The C compiler
  • LD: The linker
  • CFLAGS: C compiler flags
  • CXXFLAGS: C compiler flags
  • LDFLAGS: Linker flags
  • LDLIBS: Libraries to link

Basic Makefile

Let's start with a simple Makefile:

CC = gcc
CXX = g++
LD = g++
CFLAGS = -g
CXXFLAGS = -g
LDFLAGS = -g
LDLIBS =

SRCS = main.cpp support.cpp
OBJS = $(SRCS:.cpp=.o)

all: main
main: $(OBJS)
    $(LD) $(LDFLAGS) $(OBJS) $(LDLIBS) -o main

clean:
    rm -f $(OBJS)

This Makefile defines the following:

  • The C and C compilers to use
  • The compilation and linking flags
  • The source files and object files
  • The final executable

The all target is the default target, which will be built when you run make. The main target depends on the object files, which in turn depend on the source files. The clean target will remove the object files.

Using Make

To use this Makefile, simply type the following command in the terminal:

make

Make will read the Makefile and build the project. You can also specify a specific target by typing:

make <target>

For example, to build only the object files, you would type:

make OBJS

The above is the detailed content of How to Create a Simple C Makefile?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn