2.5.2. Example: Building a C program using a Makefile


To build a sample C program by using a Makefile, follow the steps in this example.

Procedure

  1. Create a directory hellomake:

    $ mkdir hellomake
  2. Change to the created directory:

    $ cd hellomake
  3. Create a file hello.c with the following contents:

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
      printf("Hello, World!\n");
      return 0;
    }
  4. Create a file Makefile with the following contents:

    CC=gcc
    CFLAGS=-c -Wall
    SOURCE=hello.c
    OBJ=$(SOURCE:.c=.o)
    EXE=hello
    
    all: $(SOURCE) $(EXE)
    
    $(EXE): $(OBJ)
            $(CC) $(OBJ) -o $@
    
    %.o: %.c
            $(CC) $(CFLAGS) $< -o $@
    
    clean:
            rm -rf $(OBJ) $(EXE)
    重要

    The Makefile recipe lines must start with the tab character. When you copy this example from the documentation, the cut-and-paste process might paste spaces instead of tabs. If this happens, correct the issue manually.

  5. Run make:

    $ make
    gcc -c -Wall hello.c -o hello.o
    gcc hello.o -o hello

    This creates an executable file hello.

  6. Run the executable file hello:

    $ ./hello
    Hello, World!
  7. Run the Makefile target clean to remove the created files:

    $ make clean
    rm -rf hello.o hello

Additional resources

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

关于红帽文档

Legal Notice

Theme

© 2026 Red Hat
返回顶部