make:***没有规则来制作目标`main.c',`main.o'需要.停止

Ang*_*gus 5 c unix gnu-make

functions.h

#include<stdio.h>
void print_hello(void);
int factorial(int n);
Run Code Online (Sandbox Code Playgroud)

main.c中

#include<stdio.h>
#include<functions.h>
int main()
{
 print_hello();
 printf("\nThe factorial is: %d \n",factorial(5));
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

你好ç

#include<stdio.h>
#include<functions.h>
void print_hello()
{
 printf("\nHello World!\n");
}
Run Code Online (Sandbox Code Playgroud)

factorial.c

#include<stdio.h>
#include<functions.h>
int factorial(int n)
{
 if(n!=1)
 {
  return(n*factorial(n-1));
 }
 else
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

生成文件

exec : \
 compile  
    echo "Executing the object file"
    ./compile 

compile : main.o hello.o factorial.o
    echo "Compiling"
    gcc -o compile $^

main.o : main.c functions.h
    gcc -c main.c -I./INCLUDE -I./SRC

hello.o : hello.c functions.h
    gcc -c hello.c -I./INCLUDE -I./SRC

factorial.o : factorial.c functions.h
    gcc -c factorial.c -I./INCLUDE -I./SRC
Run Code Online (Sandbox Code Playgroud)

文件夹:make_example\INCLUDE\functions.h文件夹:make_example\SRC\main.c文件夹:make_example\SRC\hello.c文件夹:make_example\SRC\factorial.c文件夹:make_example\makefile

将make文件编译为"desktop:〜/ make_example $ make时出错

make:*没有规则来制作目标main.c', needed bymain.o'.停止."

请帮我理解为什么会出现这个错误

thi*_*ton 8

当你运行make它试图让第一目标文件(在exec),这取决于compile,依赖于main.o,它依赖于main.c.没有文件main.c,只有SRC/main.c.没有规则来调用文件main.c,并且没有预先存在main.c,因此make有错误并退出.

您可以使用VPATH或修复此问题vpath:

VPATH = SRC INCLUDE 
Run Code Online (Sandbox Code Playgroud)


Wil*_*ell 6

您的 main.c 位于子目录 src 中,make 不知道去那里查看。有很多选项,其中最简单的是在makefile中写入“src/main.c”而不是“main.c”。您也可以将 main.c 上移一个级别,或者将 makefile 移至 src/ 并在那里构建,或者将一个 makefile 放在顶层,将 cds 放入 src 并调用 make(这是递归 make,许多人认为这是“有害的”,但在许多(大多数)情况下完全没问题。)您也可以使用 VPATH 指令,但如果您选择这样做,请注意这不适用于所有版本的 make。