Pregunta

I was studying C from K & R and got confused in part 4.4 of the book, when it is referring to scope rules. Before I go any further, let me just post the source file I am working on.

#include <stdio.h>

void first(void);

int main(void) {
    printf("In main.\n");

    first();
    second();

    return 0;
}

void first(void) {
    printf("In first.\n");
}

void second(void) {
    printf("In second.\n");
}

Now, unless I am more stupid than I imagine, the book gave me the idea that function prototypes (in the same file as the definition of the function) exist for scoping reasons. That is, they exist to allow the function to be declared at the top of a compiled file to for the rest of a source file to be notified for the existence of an "object" if I may so call it, ahead of time.

My issue with the above code is that in an Arch Linux Virtual Machine I am working on with GCC version 4.7.1 the above file can NOT compile and gives the following error: conflicting types for second.

However, when the very same code is run into my physical machine, sporting Ubuntu 12.04 with GCC version 4.6.3 it compiles just fine.

My question is: Is this a compiler feature? Because if it is not, I am surprised it compiles at all, seeing as there is no function prototype for second, main (if I have understood it correctly) should not be able to know about second's existence.

¿Fue útil?

Solución

The "conflicting types" error message happens because most C compilers, upon encountering a function that has not been declared yet, will implicitly declare a prototype for that function returning an int. So when second() is encountered in main(), GCC 4.7.1 is inferring the following definition:

int second();

Then when the compiler reaches the function definition, notices that the inferred prototype's signature does not match the definition's signature, and aborts with an error.

As far as why 4.6.3 successfully compiles this code, the following is a guess. GCC 4.6.3 may have some bug (or feature, you decide) that allows function implementations to differ from their prototypes by their return type. Since C allows functions with non-void return types to terminate without returning anything (which makes their return value undefined), this could simply be a case of two sub-optimal things canceling each other out.

(The behavior in 4.6.3 could also be a change in default compiler options between versions, or perhaps you are invoking the compiler with different options.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top