麻烦写我的第一个Makefile

时间:2018-06-16 03:51:37

标签: c makefile gnu-make

所以这是我的Makefile:

    # My First Makefile
    HEADERS = stdio.h

    all: main.o input.o output.o
             cc -o all main.o input.o output.o

    main.o: main.c $(HEADERS)
             cc -c main.c -o main.o

    input.o: input.c $(HEADERS)
             cc -c input.c -o input.o
    output.o: output.c $(HEADERS)
             cc -c output.c -o output.o


    clean:
           -rm -f *.o
           -rm -f all

以下是input.c:

 #ifndef __STDIO_H__
 #define __STDIO_H__

 #include <stdio.h>

 void getChar()
 {

    getchar();

 }


 #endif 

以下是output.c:

 #ifndef __STDIO_H__
 #define __STDIO_H__

 #include <stdio.h>

 void putChar(char c)
 {

    putchar(c);

 }

 #endif

以下是main.c:

#ifndef __STDIO_H__
#define __STDIO_H__
#include <stdio.h>

int main()
{
   char c;  
   while ((c = etChar()) != '\n')
   {
      putChar(c);
   }


}

#endif

然而每当我按下&#34; make&#34;终端中的命令,

我明白了:

make: *** No rule to make target `stdio.h', needed by `main.o'.  Stop.

cc指的是clang

我在这里做错了什么?

我试图通过使用$(HEADERS)

来习惯$(ARGS)

但似乎clang编译器不接受这个。

您认为我应该使用gcc吗?

2 个答案:

答案 0 :(得分:1)

在你的情况下:

“make”将在当前目录中查找stdio.h,并抱怨未找到标题。

为了解决这个问题,你应该提到stdio.h所在的完整路径,例如:

HEADERS = /usr/include/stdio.h

理想情况下,如果要检查是否存在标准头文件,例如stdio.h,则应使用automake和autoconf等工具,这些工具会自动生成Makefile。这是一个指向autoconf文档的链接: https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html

答案 1 :(得分:1)

不必在Makefile中编写 stdio.h 。 GCC将自动在DEFAULT PATH中搜索它(/ usr / include,....)。只有在使用自己的头文件时才将头文件写入Makefile中的tar。

# Makefile

# define CC
CC := gcc

# define final targets
TARGETS := main

# just trigger $(TARGETS)
all: $(TARGETS)

# build main from main.o, input.o, output.o
main: main.o input.o output.o
    $(CC) -o $@ $^

# build main.o/input.o/output.c from main.c/input.c/output.c
%.o: %.c
    $(CC) -c -o $@ $<

# trigger $(TARGETS), then run ./main
run: $(TARGETS)
    ./main

clean:
    -rm $(TARGETS)
    -rm *.o

# define targets which are not bound to file
.PHONY: all clean run