c - 如何正确设置 makefile 并在此 C 程序中获得正确的结果

标签 c makefile

我写了一个由这些文件组成的 C 代码:main.ckernel.cfunzione.cfunzione.hstruttura.h。以下是文件:

main.c:

#include <math.h>
#include "stdio.h"

#include "struttura.h"
#include "funzione.h"

struttura o;

#include "kernel.c"

int main(void){

  pincopallo();
  return 0;
}

kernel.c

void pincopallo(void){  
printf("o.x=%f\n",o.x);
printf("o.y=%f\n",o.y);
}

funzione.cu

#include "struttura.h"

void funzione(struttura* a){
  (*a).x  = 450;
  (*a).y  = 150;
}

funzione.h

#include "struttura.h"
void funzione(struttura* a);

struttura.h

#ifndef STRUTTURA_H
#define STRUTTURA_H

typedef struct{
  float x;
  float y;  
}struttura;

#endif /* STRUTTURA_H */

我的目标是显示包含在 funzione.c 文件中的值(我根本不想修改它,就像 struttura.h 一样)。但是,当我使用自己编写的 makefile 编译它时,我得到以下结果:

o.x=0.000000
o.y=0.000000

而不是值 450 和 150。

这是生成文件:

enter CC=gcc
CFLAGS=-Wall
OBJS = main.o funzione.o 

all: eseguibile

eseguibile: $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) -o eseguibile -lm

main.o: main.c funzione.h struttura.h
    $(CC) -c $(CFLAGS) main.c

funzione.o: funzione.c funzione.h struttura.h
    $(CC) -c $(CFLAGS) funzione.c

clean:
    rm -rf *.o eseguibilecode here

(注意标签)。我确信 makefile 并不完全正确:事实上,如果第一次运行它,它会一直编译。但是,如果我在 kernel.c 中修改某些内容(例如,我将 printf("o.x=%f\n",o.x); 更改为 printf("o.x =%d\n",o.x);) 然后我尝试再次编译,终端将显示以下消息:make: Nothing to be done for all. 在这种情况下我需要执行 make clean 并再次编译才能获得明显的错误消息: 错误:“struttura”没有名为“z”的成员 printf("o.x=%f\n",o.z);

所以基本上我的问题是 2:

  • 怎样才能得到正确的结果?

  • 我应该如何修改 makefile 以便每次我修改 kernel.c

    时它都能编译

最佳答案

main.c 如果 kernel.c 发生变化,应该重新编译,因为你在其中 #include kernel.c,但是 make 不知道依赖关系。您也可以将它添加到 main.o,如下所示:

main.o: main.c funzione.h struttura.h kernel.c
    $(CC) -c $(CFLAGS) main.c

关于c - 如何正确设置 makefile 并在此 C 程序中获得正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583259/

相关文章:

c - 试图获取操作时间和接收时间 0 秒

c++ - 基于 Python 的构建工具

java - 生成文件问题

c - 需要帮助查找 C 程序中的错误(与 char** 复制相关)

c - 我写下要扫描的第一个数字,按回车键后,它会在 Windows 中显示 'not responding' 消息

c - 这 4 项 :character, 数组、字符串、文字之间有什么区别。在C?

Git:在未跟踪的构建目录中使用 Makefile

具有多个程序的c++ makefile,源文件的自动检测

c++ - cuda 共享库链接 : undefined reference to cudaRegisterLinkedBinary

php - 无法在 C 中的 PHP_FUNCTION() 中调用另一个函数