简体   繁体   中英

Correct way to define a prototype

Came across a situation where I was in doubt how to define the prototype the correct way. It´s easier to just look at a simple example:

Document Ac:

#define foo bar

void mon() {
  foo();
}

Document Bc:

void bar() {
  Do something;
}

Gives following warning:

Warning: Function does not have a full prototype

Normally I would solve it by:

extern void foo(void);

But as example show, the function dont exactly exist but is defined to point on another function. What is the correct way to make a prototype for this?

I think, that what happens is the following:

The compiler replaces the macro foo with bar but since at that stage bar is not declared anywhere as a function the compiler will complain, that it cannot find it.

Please see more: Are prototypes required for all functions in C89, C90 or C99?

If the compiler encounters the declaration extern void foo(void); after the #define foo bar for the same source file, it will parse it as extern void bar(void); And the linker will just solve the bar symbol.

Note that you definition of bar is not consistent with the declaration above. The definition of bar should read:

void bar(void) {
    // Do something;
}

in C, unlike C++, an argument list of (void) is subtly different from an empty argument list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM