未定义的引用函数 [英] Undefined Reference to a function

查看:209
本文介绍了未定义的引用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Linux和我有以下文件:

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

功能 F1() fileB.h 声明,并在 FILEB定义的.cpp 。我需要使用的功能 fileA.c ,所以我声明了函数

 的extern无效F1();

fileA.c

不过,在编译过程中,我得到了错误

  fileA.c:(+的.text 0x2b7):未定义引用'F1'

什么是错的?

感谢您。

ETA:感谢我收到的答案,我现在有以下几点:

在fileA.h,我有

 的#include fileB.h
#包括main.h#IFDEF __cplusplus
为externC
#万一
无效F1();

在fileA.c,我有

 的#include fileA.h

在fileB.h,我有

 的externC无效F1();

在fileB.cpp,我有

 的#includefileB.h为externC无效F1()
{}

不过,我现在有误差

  fileB.h:错误:预期的标识符或'('前字符串常量


解决方案

如果你真的编译 fileA.c 为C,而不是C ++,那么你需要做确保该函数具有正确,C兼容的连接。

您可以使用的extern 关键字的一个特例做到这一点。无论是在声明和定义:

 的externC无效F1();
为externC无效F1(){}

否则的C连接器会寻找一个只有真正与一些重整C ++名称存在一个功能,不支持的调用约定。 :)

不幸的是,虽然这是你必须在C ++中做什么,语法是不是在C 有效。你必须让的extern 可见只对C ++ code。

所以,一些preprocessor法宝:

 的#ifdef __cplusplus
为externC
#万一
无效F1();

不完全是pretty,但它是你付出的共享两种语言的code之间的头的价格。

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

解决方案

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.

这篇关于未定义的引用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆