开发者

Calling a function from the same header file from two C++ files in the same project

I have a program consisting of 3 files:

main.c; other.c and event.h

event.h has a function called 'event()'.

I'd like to call the event() function from both main.c and other.c. At the top of both main.c and other.c I include the line

#include "event.h"

...and within each of the .c files I have the lines

event();

However I receive the following compile errors (Visual C++)

"fatal error LNK1169: one or more multiply defined symbols found"

"error LNK2005: _event@16 already defined in main.obj开发者_如何学编程"

...What am I doing wrong?


You have two choices: either don't define the function in the header, or define it as inline. The first is covered in other answers, and the latter is as easy as prepending "inline" to the function definition:

inline
void example() {
  do_stuff();
}

Whether you want to define the function inline or not is, today, all about your convenience and not about optimization. Which is easier for you? Inline functions are almost always easier to begin with (i.e. prototyping and first versions); you can always reverse that decision, if needed, later.


The definition of the function ie its code can only be given in one place.

The header should include just the declaration of the event function and the code implementing the function needs to be in a .c file.

e.g.

in event.h

void event();

and in any ONE .c file - could be either of main.c or other.c or probably better a separate file event.c

void event()
{
    printf( "Hello\n" );
}


You should not define event() in event.h. Because event.h is included both in main.c and other.c, it ends up being defined twice.

You need to declare it in event.h, with the function signature, such as:

void event();

And put the definition in an event.c file where you will put the function body. The function will be defined only in this event.c file, and the two other .c files will only include the declaration.


I suppose you have defined event() in event.h, like this:

void event()
{
 ....
}

But in header you have to declare function and then define it in .cpp So you have to do the following: event.h

// declaration
void event();

event.cpp

#include "event.h"
// implementation
void event()
{
 ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜