user9022577
user9022577

Reputation:

Static and multiple functions with same name in different headers

I have two header files which define two functions with same name and different parameters. I know c doesn't support function overloading, but I thought adding static to a function declaration would allow me to declare two functions with the same name with a caveat that I could only access them in a same source file. Anyway it is not working and I'm not sure why not? Is my understanding wrong?

Example: file1.h has following function:

static bool do_something(int a);

file2.h has following function:

static bool do_something(char b);

main.cpp has both headers included:

#include "file1.h"
#include "file2.h"

Example error:

file1.h:26:13: error: conflicting types for ‘do_something’
static bool do_something(int a);

file2.h:23:13: note: previous declaration of ‘do_something’ was here
 static bool do_something(char b);

Thanks in advance.

Upvotes: 1

Views: 4367

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

bool do_something(int a); is a prototype. It tells the compiler that function do_something requires a parameter of type int and returns a value of type bool.

When you call this function, the compiler can now check that you pass a correct argument and assign the return value to a variable of the correct type.

As C does not have function overloading, you will understand that there can only be one definition of the function in any one compilation unit. A compilation unit is a .c source file with all .h files included.

So the above description has no influence on linking whatsoever. If the function is not called, the prototype is not needed; if there is a prototype, it will not require the function to exist. And if the function is called, it may exist in any of the source files or libraries that are linked into the executable.

The keyword static for a function definition indicates that the function will only be visible to other functions in the compilation unit (and so must exist in source in the compilation unit). Inlcuding the static keyword in a .h file makes no sense as it will tell each source file in which the .h file is included that the function, if used, exists in that source file.

This description does have influence on the linking process, in the sense that if the function is used, it must be present in the current source file.

In your case, you must decide which of the two protoypes is correct and fix the .h file accordingly - or declare a second, different function, that takes the other parameter e.g. do_something_else.

Upvotes: 2

Related Questions