Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c++ - Undefined Reference to a function

I'm using Linux and I have the following files:

main.c, main.h
fileA.c, fileA.h
fileB.cpp, fileB.h

The function F1() is declared in fileB.h and defined in fileB.cpp. I need to use the function in fileA.c, and so I declared the function as

extern void F1();

in fileA.c.

However, during compilation, I got the error

fileA.c: (.text+0x2b7): undefined reference to `F1'

What is wrong?

Thank you.

ETA: Thanks to the answers I've received, I now have the following:

In fileA.h, I have

#include fileB.h
#include main.h

#ifdef __cplusplus
extern "C" 
#endif
void F1();

In fileA.c, I have

#include fileA.h

In fileB.h, I have

extern "C" void F1();

In fileB.cpp, I have

#include "fileB.h"

extern "C" void F1()
{ }

However, I now have the error

fileB.h: error: expected identifier or '(' before string constant
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're really compiling fileA.c as C, not C++, then you need to make sure that the function has the proper, C-compatible linkage.

You can do this with a special case of the extern keyword. Both at declaration and definition:

extern "C" void F1();
extern "C" void F1() {}

Otherwise the C linker will be looking for a function that only really exists with some mangled C++ name, and an unsupported calling convention. :)

Unfortunately, whilst this is what you have to do in C++, the syntax isn't valid in C. You must make the extern visible only to the C++ code.

So, with some preprocessor magic:

#ifdef __cplusplus
extern "C"
#endif
void F1();

Not entirely pretty, but it's the price you pay for sharing a header between code of two languages.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...