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

How to Create a Simple C Makefile?

DDD
Release: 2024-12-04 16:17:15
Original
638 people have browsed it

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)
Copy after login

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
Copy after login

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

make <target>
Copy after login

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

make OBJS
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template