Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C linking stage generates no warning

Tags:

c

linux

gcc

linker

I have the following files:

main.c :

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

f.c:

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?

like image 385
Dan Lincan Avatar asked Mar 21 '26 20:03

Dan Lincan


2 Answers

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 f.c (definition).

Don't lie to the compiler.

like image 112
pmg Avatar answered Mar 23 '26 19:03

pmg


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.

like image 23
Flexo Avatar answered Mar 23 '26 19:03

Flexo