我有以下两个 .c
文件
main.c
#include <stdio.h>
int print();
int show(int);
int main()
{
int i = 0;
float x = 1.0;
int y = *((int*)(&x));
print();
i = show(5);
printf("%d", i);
printf("\n%d", y);
return 0;
}
foo.c
#include <stdio.h>
void print()
{
printf("Hello World !!\n");
}
float show()
{
return 1;
}
这是我的makefile
CC = gcc
CFLAGS = -I. -Wall -pedantic -Wconversion
.PHONY: clean
%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS)
main: main.o foo.o
$(CC) -o main main.o foo.o $(CFLAGS)
clean:
rm -rf *.o
rm -rf main
这是输出
Hello World !!
1065353216
1065353216
如果我构建上面的,绝对没有错误。似乎在链接 gcc
时并不关心这两个函数具有不同的返回类型和不同的参数列表。
第二点是,在函数 show
中,不是进行从 float
到 int
的隐式转换,而是复制位模式,我已经使用第二个 printf
调用对其进行了验证。
为什么会出现上述情况?我知道这不会发生在 g++
中,因为名称修改,但这不是一个严重的问题吗?
最佳答案
诀窍是在头文件 (foo.h
) 中声明您的函数,然后将该头文件包含在源文件 (foo.c
) 中。还将头文件包含在调用 foo.h 中声明的函数的任何源文件(例如 main.c
)中。
在 foo.c
中包含 foo.h
允许编译器验证函数声明是否与函数定义匹配。在 main.c
中包含 foo.h
让编译器验证 main.c 是否正确使用函数,并允许编译器进行任何必要的类型转换。
如您所见,通过在 main.c 中错误地声明函数来欺骗编译器,对您没有好处。
foo.h
void print( void );
float show( void );
main.c
#include <stdio.h>
#include "foo.h"
int main()
{
int i = 0;
print();
i = show();
printf("%d\n", i);
return 0;
}
foo.c
#include <stdio.h>
#include "foo.h"
void print( void )
{
printf("Hello World !!\n");
}
float show( void )
{
return 2;
}
关于c - GCC 链接函数时没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828503/