Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "no previous prototype for function" in this little sample?

I have a very simple Objective-C sample

#import <Foundation/Foundation.h>

int littleFunction();

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool 
    = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");

    [pool drain];
    return 0;
}

int littleFunction()
{
    return 0;
}

With this code I get a "no previous prototype for function" warning for littleFunction but as you can all see there is a declaration before main. What is wrong here? It seem the compiler is unable to match the declaration with the function implementation.

If I change both like this:

int littleFunction(void)

it works perfectly. I am using the latest Xcode 4

like image 428
TalkingCode Avatar asked Sep 04 '11 06:09

TalkingCode


Video Answer


2 Answers

In C, int littleFunction(); is not really a prototype. It doesn't specify how many (or what sort of) parameters the function accepts.

The actual wording in C99 is in §6.7.5.3 item 14:

An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.124

The footnote refers to this section in the Future language directions:

6.11.6 Function declarators
The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

(Note: this is still present in the C11 draft I have (n1570).)

Back in §6.7.5.3, item 10:

The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.

So you have to explicitly specify int foo(void); if you want to prototype a function that doesn't take parameters. Objective-C has the same rules.

like image 172
Mat Avatar answered Jan 15 '23 08:01

Mat


I think the problem is that you did not use "static" for a global function.

Please refer to the following:

no previous prototype for `foo'

This means that GCC found a global function definition without seeing a prototype for the function. If a function is used in more than one file, there should be a prototype for it in a header file somewhere. This keeps functions and their uses from getting out of sync

If the function is only used in this file, make it static to guarantee that it'll never be used outside this file and document that it's a local function

like image 31
basicthinker Avatar answered Jan 15 '23 09:01

basicthinker