当在某些标头中声明时,双类型的C函数有时会起作用



我遇到了一个奇怪的问题,有时这个函数并不总是有效的,只有在调用它的同一个头中声明它时才有效。。。这真的很奇怪,因为编译器似乎甚至忽略了包含函数的文件是否包含。。。

double mapRange(double value, double r1, double r2, double n1, double n2)
{
double res = n1+(value-r1)*((n2-n1)/(r2-r1));
printf("dividingby: %f", res);putchar('n');
return res;
}

正如您所看到的,当它打印值时,它是正确的,但是当我打印从另一个函数(如main(返回的值时,我会得到垃圾数。。。最糟糕的是,我自己在一个文件上测试了它,它运行得很完美,我知道这似乎是我的错误,但我真的找不到对此的解释。。。有人遇到过这样的事情吗?我的编译器坏了吗?C中有我不知道的限制吗?我也知道,我没有比这更多的代码可以提供,这让诊断变得困难,但它来自一个不那么小的大学项目。。。

编辑1:好的,所以

//main.c

#ifndef UTIL_H
#define UTIL_H
#include "util.h"
#endif /*UTIL_H*/
int main(int argc, char *argv[]) {
Matrix* volcan = readVolcano("test.txt");
double t;
mapRange(7.0, 1.0, 9.0, 0.0, 1.0,&t);
printf("%fn..n", t);
mat_printinfo(volcan);
mat_printmat(volcan, NULL);
weighted_volcano(volcan, NULL, NULL, NULL);
mat_free(volcan);
return 0;
}

//util.c

#include "util.h"

/*
Retorna una transformacion de value que esta entre r1 y r2 a un valor que esta
entre n1 y n2, con tal que tenga la misma relacion con el rango [n1, n2] como
value tenga con el rango [r1, r2]
*/

double mapRange(double value, double r1, double r2, double n1, double n2, double* result)
{
double res = n1+(value-r1)*((n2-n1)/(r2-r1));
printf("dividingby: %f", res);putchar('n');
if(result!=NULL)
*result = res;
return res;
}

我绝对相信定义中没有重复,我也多次重建了这个项目。。。

D:CodeCvolcancc1.exe    [Warning] command line option '-std=c++11' is valid for C++/ObjC++ but not for C
D:CodeCvolcanmain.c In function 'main':
52  19  D:CodeCvolcanmain.c [Warning] initialization makes pointer from integer without a cast
D:CodeCvolcanmain.c In function 'open_volcano':
91  7   D:CodeCvolcanmain.c [Warning] assignment makes pointer from integer without a cast
D:CodeCvolcanmain.c In function 'test_volcano':
119 13  D:CodeCvolcanmain.c [Warning] assignment makes pointer from integer without a cast
D:CodeCvolcancc1.exe    [Warning] command line option '-std=c++11' is valid for C++/ObjC++ but not for C
D:CodeCvolcanvolcantobmp.c  In function 'weighted_volcano':
38  6   D:CodeCvolcanvolcantobmp.c  [Warning] assignment makes pointer from integer without a cast
40  6   D:CodeCvolcanvolcantobmp.c  [Warning] assignment makes pointer from integer without a cast
D:CodeCvolcancc1.exe    [Warning] command line option '-std=c++11' is valid for C++/ObjC++ but not for C

IDE 的输出

编辑2:看来问题出在这里了

//util.h

#include "headers.h"

它是空的。。。

根据您的描述,您的"代码库"中很可能还有另一个"mapRange"函数。

为了隔离这个问题,我建议将"mapRange"函数重命名为唯一的函数,比如在main((中添加今天的日期(mapRange_20181127(,留下mapRange调用。如果你的"代码库"包含另一个名为"mapRange"的函数,你将不会面临任何错误,因为链接器会找到"其他"mapRange。

如果是这样的话,选择另一个有意义的名字可以解决你的问题。

希望这能有所帮助!

更新:我想当我打字时,你发布了更多详细信息,你得到了答案:(。

@StevenSummit为我提供了它需要的解决方案util.h 中函数的原型声明

最新更新