【问题标题】:Having trouble with makefile: it doesn't behave the way I've been taught it should and I'm not sure what to domakefile 遇到问题:它的行为不像我被教导的那样,我不知道该怎么做
【发布时间】:2019-11-17 18:46:04
【问题描述】:

我正在为 C 类教学做一个项目。我的想法是使用设置在不同源文件中的函数创建 mandelbrot 集的可视化,并使用标题和生成文件链接在一起。我可以确认 100% 的 complex.c(如下)正常工作,并且在编译时没有警告或错误。然而,对于这个项目,我已将类型定义移至头文件,并且在我的 main.c 文件中有一个“虚构”类型的全局变量。我的 mandelbrot.h 头文件引用了该全局变量。

当我尝试使用我的 makefile 进行编译时出现两个错误。这些错误是:

1. "error: unknown type name "img""

这发生在我移动“typedef struct{}img;”之后到头文件。

2. Undeclared variable c referenced for first time at line <whatever> in mandelbrot.c

我在 main.c 中声明了 img c,在 mandelbrot.h 中声明了 extern img c。我不知道这是怎么回事,因为我们的教授相当明确地说要在 main.c 中将变量声明为全局变量,然后通过 mandelbrot.h 中的 extern 引用它,以便在 mandelbrot.c 中看到它

我试图明确表示,因为如果我做错了什么,我想跟踪并找到它(另外,我们应该使用显式的 makefile,而不是使用特殊变量,如 $(CC) 等。最后可执行文件是 mandelbrot。

mandelbrot: main.o mandelbrot.o complex.o
    gcc -o -Wall mandelbrot main.o mandelbrot.o complex.o

main.o: main.c complex.h mandelbrot.h
    gcc -c main.c

mandelbrot.o: mandelbrot.c complex.h mandelbrot.h
    gcc -c mandelbrot.c

complex.o: complex.h complex.c
    gcc -c complex.c -lm

clean:
    rm *.o

这是我的源代码(所有头文件还包括我的函数原型,但我没有复制它们):

//complex.h
//Components of complex number.
typedef struct{
    float r;
    float j;
} img;

这里是源文件:

//complex.c
#include <stdio.h>
#include <math.h>

img function(c){
//does something with the global variable c
}

我有第二个函数,它处理一些涉及 mandelbrot 集的检查。该函数位于一个单独的文件中,并且具有:

//mandelbrot.h
//Reference an external global variable. 
extern img c;

还有源文件:

//mandelbrot.c
#include "complex.h"
img mandelbrot(int n){
    //Code that does stuff
    if (absolute_value(c, n-1) > 1000000){
    //does something
    }
}

我有最后一个源文件:

//main.c
#include "mandelbrot.h"
#include "complex.h"
img c;

main(){
    //does some stuff.
}

【问题讨论】:

  • 你有两个主要功能,这是不允许的。 complex.c 中的那个有一个与 main.c 中的全局同名的局部变量,这看起来很混乱。 mandelbrot.c 文件引用全局 c,但不包括声明为 extern 的 mandelbrot.h 标头。
  • 您的问题与 makefile 无关,它们只是您的 C 代码中的错误。
  • 使main.o依赖于makefile中的mandelbrot.h并不能让它真正使用它,你仍然需要#include "mandelbrot.h"
  • 只是为了确认 - 您是否让每个 .c 文件都包含其关联的 .h 文件?例如,complex.c 是否包含 complex.h
  • 请注意,按照惯例,如果extern img c; 出现在“mandelbrot.h”中,那么img c; 应该出现在“mandelbrot.c”中。另一种方法是在main 函数内声明img c,然后将其传递给任何需要它的函数。我怀疑后者才是你真正想要的,因为我认为你的程序中需要多个复数。

标签: c makefile header-files


【解决方案1】:
  1. 可以通过将#include "complex.h"(由C保留,使用其他)来修复mandelbrot.h

  2. 可以通过将#include "mandelbrot.h" 放入mandelbrot.c 并从mandelbrot.cmain.c 中删除#include "complex.h" 来修复。

  3. 可以通过将#include "complex.h" 放入complex.c 来修复。

  4. 可以通过将-o -Wall mandelbrot更改为-o mandelbrot -Wall来修复。

你真的需要开始使用标题保护了。

【讨论】:

  • 所以我做了一些你建议的标题更改(一些我已经做过或者是我原来的帖子中的错别字)。这些更改减少了错误和警告的数量,但也导致了一组单独的新错误。最后,我将#include 和#include 移到了main.c 文件中。根据您的建议,我还稍微更改了 makefile 以反映更简单的依赖关系。
猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多