【问题标题】:Eclipse: C-code in C++ static lib, referenced by C++ lib results in undefined referenceEclipse:C++ 静态库中的 C 代码,由 C++ 库引用导致未定义的引用
【发布时间】:2014-03-03 12:28:31
【问题描述】:

我在这里阅读了几乎所有“未定义的参考”主题,花了 2 天时间尝试不同的链接选项,但没有任何结果。我很绝望!

我在使用 Eclipse 3.6.1 和 GCC 4.4.7 的 Linux Red Hat 平台上。

我正在将一个大型项目从 Solaris 工作室(它工作的地方)移植到 Eclipse。 我有 C++ 静态库项目(例如 Common_Lib),其中包括 transformations.c + .h 文件 - 纯 C 代码。

transformations.h 文件包含在

#ifndef TRANSFORMATIONS_H_
#define TRANSFORMATIONS_H_

#ifdef __cplusplus
extern "C" {
#endif

void foo(int *x);

#ifdef __cplusplus
}
#endif
#endif

/* transformations.c */
#include "transformations.h"

void foo(int *x)
{
   /* calculations on x*/
}

我有另一个 C++ 静态库项目(例如 Factory_Lib),其方法 Do_Transform() 从 transformations.h 调用 foo()。这个项目是正确构建的。

#ifndef FACTORY_H
#define FACTORY_H
#include "transformations.h"

class CFactory
{
   public:
   void Do_Transform(int *x);
};

// factory.cpp
#include "factory.h"

void CFactory::Do_Transform(int *x)
{
   foo(x);
}

最后一个 - 可执行 - C++ 项目(例如 Worker),它调用 Factory_Lib 的 Do_Transform(),它调用 foo()。

#include factory.h

int main
{
   CFactory fact = new CFactory();
   int x=0;

   fact.Do_Transform(&x);

   return 0;
}

Worker 拒绝构建(链接),出现“undefined reference to foo()”。

如果从 Worker 的 main()直接调用 foo(),问题不会出现!

在 Worker 项目中,我尝试在 Settings->Linker 引用中引用 Reference projects 中的 Common_Lib 作为附加库 -l 在链接器中没有 引用的项目等。我尝试了很多组合,但没有成功。

我必须怎么做才能让它工作?!?!?我的想法已经用完了。

提前谢谢你!

【问题讨论】:

  • transformations.h 文件最后有#endif 吗?

标签: c++ c eclipse undefined-reference gcc4.4


【解决方案1】:

您可以通过以下方式获得好运:-lFactory -lCommon,顺序很重要。

【讨论】:

  • 谢谢!这解决了我的问题!但我不明白为什么。你能解释一下这背后的逻辑吗?
【解决方案2】:

既然您拥有 Common_Lib 和 Factory_Lib 的代码,为什么不使用通用 c++ 编译器本身来编译它们。我的意思是将两个库编译为 C++ 库(除了从 transformation.h 中删除 extern "C" 之外不需要更改代码)

我不明白你为什么在这里需要 extern?这里不涉及 C 编译器。这两个库都是 C++。

【讨论】:

  • Common_Lib 是 C++ 项目,包含纯 C 文件:transformations.c。该文件是用 gcc 而不是 g++ 编译的。其中的代码仅为 C,并且必须保持为仅 C。
  • 您在制作工人时是否链接了两个档案。否则我没有看到问题。
猜你喜欢
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多