tags:

views:

69

answers:

3

Hello Friends,

I'm writing a C University project and stumbled upon a compiler behavior which I don't understand.

In this file http://code.google.com/p/openu-bsc-maximveksler/source/browse/trunk/20465/semester/tasks/maman14/alpha/maman14/assembler/phaseOne.c?r=112 I've added a call to function named freeAsmInstruction(). This function is defined in file named lineParser.c, yet I haven't updated the matching lineParser.h header file to include this function declaration.

Why does this code compile? I would expect that gcc would fail to compile phaseOne.c until the correct lineParser.h is updated with the declaration of freeAsmInstruction().

I would appreciate an explanation.

Thank you, Maxim

+3  A: 

The GCC compiler is assuming a particular default function signature. To get a warning about this, compile with the -Wall flag:

gcc -Wall -c phaseOne.c

this will give you a warning of the form:

phaseOne.c:2: warning: implicit declaration of function 'your func here'

Unless you have good reason, you should always compile with the -Wall flag, and probably other warning flags too.

anon
Thank you for the answer.
Maxim Veksler
For example, I generally use -pedantic -Wall -Wextra -Wwrite-strings -Wconversion -Werror, and then remove warning flags if necessary.
Steve Jessop
@Steve It would probably a great boon to humanity if GNU turned at least -Wall and -pedantic on by default, and you had to use options to turn them off. But I suppose they are scared of breaking the oceans of crappy code out there.
anon
A: 

Hi,

I just wrote a sample program in two separate files:

a1.c

#include <stdio.h>

int main() {
    // using the external object

    testing();

    return 0;
}

which calls a function which exists in a2.c

void testing() {
    printf("temp\n");
}

and then all I did was compile it using the following command:

$ gcc a1.c a2.c -o a1

and it Worked

Actually, when you compiled your file did you include the other C file (lineParser.c) in the compilation step to be parsed along with your ParseOne.c file?

In that case, what I understand is that, gcc would actually parse all the symbols in the associated C files (or obj files) and replace them appropriately in the final object file to be created.

Hope this helps.

Shrey
+1  A: 

Undefined functions are not automatically an error; the compiler takes them to have a default prototype, then when your code is finally linked if there is something there of the right name it will be used. However, if the default prototype isn't what your function actually has, its arguments will be set up wrongly (think hammering a square peg into a round hole); the consequences will be unpredictable.

In most cases you should be telling the compiler to treat such cases as an error. For example, on gcc, add -Wall -Werror to every compile line, or add them to the CFLAGS in a typical Makefile.

crazyscot