Today Clang, trying to compile a program, gave me kinda an strange message. I’m not really experienced with C, so I might be doing something wrong, but the code that I actually tried is this:
#include <stdio.h>
#include <stdlib.h>
int sum(a,b);
int main ()
{
printf(sum(1,2));
return 0;
}
int sum (int a, int b)
{
return a + b;
}
As you have probably noticed, when declaring the function ‘sum’, I’m not including the param. type, so an error is expected, but the actual message Clang gives me is this:
ind.c:4:9: error: a parameter list without types is only allowed in a function definition
int sum(a,b);
^
ind.c:12:5: error: redefinition of 'sum' as different kind of symbol
int sum (int a, int b)
^
ind.c:4:5: note: previous definition is here
int sum(a,b);
^
2 errors generated.
What does Clang mean when it says it is only allowed in function definitions? Isn’t int sum(a,b); a function definition?
No,
int sum(a, b);is, or rather looks like, a function declaration, not a definition.A function declaration provides enough information for the compiler to generate calls to the function. A definition provides a declaration and, in addition, defines the code that will be executed when the function is called (the stuff between
{and}).A function declaration (that’s not part of a definition) may include the types of the parameters, or the types and their names, but not just their names. (If it includes the types, it’s a prototype.)
An old-style function definition can have just the names of the parameters, for example:
But old-style definitions and declarations are obsolescent, and are best avoided. An old-style declaration doesn’t specify the number of type(s) of the parameters, so the compiler can’t verify the correctness of calls.
Your declaration could look like this:
but it should look like this:
or even this:
Oh, and
int main ()is better written asint main(void).