Home > Backend Development > C++ > How to Create a Simple C Makefile for Compilation and Linking?

How to Create a Simple C Makefile for Compilation and Linking?

Mary-Kate Olsen
Release: 2024-12-24 14:05:10
Original
832 people have browsed it

How to Create a Simple C   Makefile for Compilation and Linking?

How to Make a SIMPLE C Makefile

Introduction

Creating a Makefile is necessary for compiling and executing a C project. This article provides an introduction to Make and a step-by-step guide on creating a simple Makefile.

Understanding Make

Make is a build dependency manager that orchestrates the order in which commands need to be executed to compile and link your C source files into an executable.

Setting Up the Makefile

For this example, we assume you have a single C file named a3driver.cpp and an imported class in /user/cse232/Examples/example32.sequence.cpp.

Building Blocks of a Makefile

Variables: Make variables allow you to store information like compiler flags and libraries. Example:

CPPFLAGS=-g -pthread -I/sw/include/root
Copy after login

Target and Dependency Lines: Target lines specify the output to be generated, while dependency lines list the files required to create the target. Example:

tool: tool.o support.o
    g++ $(LDFLAGS) -o tool tool.o support.o $(LDLIBS)

tool.o: tool.cc support.hh
    g++ $(CPPFLAGS) -c tool.cc
Copy after login

Sample Makefile

Below is a simple Makefile for your specific requirements:

CPPFLAGS=-g
LDFLAGS=-g
LDLIBS=-L/usr/lib/-llua5.2
SRCS=a3driver.cpp /user/cse232/Examples/example32.sequence.cpp
OBJS=$(SRCS:.cpp=.o)

all: a3driver

a3driver: $(OBJS)
    $(CXX) $(LDFLAGS) -o a3driver $(OBJS) $(LDLIBS)

.PHONY: clean
clean:
    rm -f $(OBJS) a3driver
Copy after login

Explanation

  • CPPFLAGS and LDFLAGS set the necessary compilation and linking flags.
  • SRCS defines the source files, and OBJS generates the corresponding object files.
  • all is the default target, and a3driver is the executable.
  • The clean target removes object files and the executable.

Conclusion

This sample Makefile should allow you to compile and execute your C project using the specified external class. Remember, Makefiles are customizable, so feel free to expand and modify them according to your needs.

The above is the detailed content of How to Create a Simple C Makefile for Compilation and Linking?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template