【问题标题】:Getting compilation error with makefile使用makefile获取编译错误
【发布时间】:2012-01-17 04:12:30
【问题描述】:

我尝试了以下示例程序来了解makefile在编译中的用法。

main.c

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

你好.c

#include<stdio.h>
#include<functions.h>
void print_hello()
{
 printf("\nHello world!\n");
}

factorial.c

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

函数.h

#include<stdio.h>
void print_hello();
int factorial(int n);

制作文件

exec : ./compile

compile : main.o hello.o factorial.o
  gcc -o compile

main.o : main.c functions.h
  gcc -c main.c

hello.o : hello.c functions.h
  gcc -c hello.c

factorial.o : factorial.c functions.h
  gcc -c factorial.c

错误:

cheetah@desktop:~/make_example$ 编译 gcc -c main.c main.c:2:22:错误:functions.h:没有这样的文件或目录 make: *** [main.o] 错误 1 猎豹@desktop:~/make_example$

已编辑:

gcc -c main.c
gcc -c hello.c
gcc -c factorial.c
gcc -o compile
gcc: no input files
make: *** [compile] Error 1

请帮助我理解为什么它会抛出一个错误,因为我已将它包含在我的 makefile 中。

【问题讨论】:

  • 注意functions.h没有给出print_hello()的原型;它只是将函数声明为采用不确定(但固定)数量的参数。要成为 C 中的原型,您必须提供 void print_hello(void);(尽管在 C++ 中,这一切都不同)。

标签: c unix


【解决方案1】:

替换

#include<functions.h>

#include"functions.h"

详细解释在这里:http://www.geekinterview.com/question_details/3379

最后,在链接阶段缺少目标文件。

compile : main.o hello.o factorial.o
  gcc -o compile main.o hello.o factorial.o

【讨论】:

  • 如果我没看错的话,那篇文章只是解释了两种风格的包含搜索位置的不同顺序。这是否解释了为什么第一个最终没有找到functions.h,假设它在当前目录中?
  • 谢谢。现在我收到错误,因为没有 i/p 文件.. 不知道我错过了什么
  • 为什么要从 makefile 中删除 functions.h - 它应该在构建目标文件的依赖项列表中。
  • @DanFego 因为,我想,functions.h 不在默认搜索位置。通常,被称为默认搜索位置的通常是您的标准系统包含目录
  • @shinkou 如果您在标头中定义一个结构,然后在某个时间更改它的定义,以便它占用更多/更少的空间。如果目标文件依赖于正确的头文件,则所有内容都会根据需要重新编译。如果他们不这样做并且您更改了一些源文件,包括更改的标头而不更改其他源文件,则只有更改的文件会被重新编译,从而导致损坏。
【解决方案2】:

除了更改源之外,您还可以使用 gcc 的 -I 选项包含当前目录以进行头文件查找。在这种情况下,您需要头文件的makefile 规则如下所示(假设头文件是当前目录):

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

正如已经指出的,您稍后在链接过程中遇到的错误是由于compile 目标中缺少输入文件。为此,还有另一种选择。您可以在 makefile 中为所有依赖项使用$^。您的compile 规则如下所示:

compile:main.o hello.o factorial.o
    gcc -o compile $^

有关 makefile 宏的一些信息,请参阅link
旁注:

  1. Guards 缺少你的头文件
  2. factorial 函数的声明和定义不匹配。
  3. 正如 Jonathan Leffler 已经提到的,请咨询print_hello 的原型

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多