简体   繁体   中英

C linking stage generates no warning

I have the following files:

main.c :

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

fc:

char *f = "linker";

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. 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 ).

Don't lie to the compiler.

You've told the compiler f is a function. 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.

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.

if you put the declaration 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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