简体   繁体   English

C链接阶段不会产生警告

[英]C linking stage generates no warning

I have the following files: 我有以下文件:

main.c : main.c:

int f(void);  
int main(void)
{
    f();
    return 0;
}

fc: FC:

char *f = "linker";

GNUMakefile: GNUMakefile:

CC = gcc
CFLAGS = -Wall -g

all: main

main: main.o f.o

main.o: main.c
f.o: f.c

clean:
    rm -rf *.o main

When running the makefile I get no compilation warnings/errors. 运行makefile时,我没有收到编译警告/错误。 Why? 为什么?

Because you lied to the compiler ... and it trusts you. 因为你骗了编译器......它信任你。

In main.c you told the compiler f is a function ( declaration / prototype ), but f is, in fact, a pointer to a (unmodifiable) character array of length 7 defined in fc ( definition ). 在main.c中,你告诉编译器f是一个函数( 声明/原型 ),但f实际上是指向fc( 定义 )中定义的长度为7的(不可修改的)字符数组的指针。

Don't lie to the compiler. 不要欺骗编译器。

You've told the compiler f is a function. 你已经告诉编译器f是一个函数。 It isn't but there's no obligation on implementations to record the type which would be needed to warn here. 它不是,但实施时没有义务记录此处需要警告的类型。 Gcc doesn't, some other implementations might. Gcc没有,其他一些实现可能会。

The workaround is to put the declaration of f into a header and include that in each translation unit which will make the error obvious. 解决方法是将f的声明放入标题中,并将其包含在每个翻译单元中,这将使错误显而易见。

if you put the declaration int f(void); 如果你把声明int f(void); into a header-file which you include from both files, you will get the exprected compiler-error. 在两个文件中包含的头文件中,您将获得明确的编译器错误。 In your present case, compile-wise all is fine. 在你目前的情况下,编译方式一切都很好。

in the makefile i miss the gcc main.c part and the ln part 在makefile中我想念gcc main.c部分和ln部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM