Agostino
Agostino

Reputation: 2811

C global function (not C++)

I'm trying to have a global function in C. Something that can be called from different files.

I know how to make a global variable by declaring it (with extern) in all files except one, and defining it in just one file (without the extern).

I need a - possibly simple - solution that can work with C89 (I'm using VS2013).

I'm compiling in C mode right now, but I'd like this to work if I switch to C++ mode later.

Thanks.

Upvotes: 1

Views: 12111

Answers (1)

hyde
hyde

Reputation: 62906

Declaration, usually in a .h file but also possible to just copy-paste to a .c file directly (for quick & dirty testing etc, for any real code you should write a proper .h file). Duplicates in same compilation unit are are ok as long as they match. You can use extern like with variables, but it's not necessary, compiler will know this is just function declaration because there is no function body, {}. Also since there is not static keyword, compiler assumes this is a global symbol.

int my_global_function(const char *string);

Definition, in exactly one .c file (more formally a compilation unit), so it will be in exactly one .o file (or library), otherwise linker will complain.:

int my_global_function(const char *string)
{
    puts(string);
    return 0;
}

Upvotes: 5

Related Questions