【问题标题】:how solve the error "undefined reference to pso(int, double*, double*)' collect2: ld returned 1 exit status"如何解决错误“未定义对 pso(int, double*, double*)' collect2: ld 返回 1 退出状态的引用”
【发布时间】:2013-11-15 03:46:04
【问题描述】:

我有一个名为 pso.cpp 的 c++ 程序,一个输入和两个输出(通过指针)如下:

void pso(int32_T Iteration, real_T *gbest, real_T *w)

我还有一个名为main.cpp的c++程序如下:

#include <math.h>
#include <stdio.h>
#include <iostream>
#include "pso.h"

using namespace std;

int main()
{
int32_T Iteration = 1000;
real_T gbest;
real_T w;
pso(Iteration, &gbest, &w);

std::cout << gbest << std::endl;
std::cout << w << std::endl;

return 0;
}

另外,pso.h 如下:

#ifndef __PSO_H__

#define __PSO_H__

/* Include files */

#include <math.h>

#include <stddef.h>

#include <stdlib.h>

#include <string.h>

#include "rt_nonfinite.h"


#include "rtwtypes.h"

#include "pso_types.h"

/* Function Declarations */

extern void pso(int32_T Iteration, real_T *gbest, real_T *w);

#endif

我通过命令g++ main.cpp -o main 执行main.cpp

但我遇到了这个错误:

main.cpp:(.text+0x29): undefined reference to pso(int, double*, double*)' collect2: ld returned 1 exit status

如何解决编程错误?

【问题讨论】:

  • 这不是问题,但是包含两个连续下划线 (__PSO_H__) 的名称和以下划线后跟大写字母的名称保留给实现。不要使用它们。
  • 我删除了所有 .h 文件中的两个连续下划线。但是你说的是下划线开头的名字。这个结构在我的编码中是否有任何变量?
  • 您发布的代码中没有这样的内容。
  • 不幸的是,发生了同样的错误。问题不是两个连续的下划线。我至少有 12 小时出现此错误 :-(
  • 正如我最初所说:“这不是问题,但是......”

标签: c++ linux compiler-errors


【解决方案1】:
g++ main.cpp -o main

应该是

g++ main.cpp pso.cpp -o main

【讨论】:

  • 我运行了您建议的命令,但我遇到了新错误:/tmp/ccSq08Uh.o: In function pso(int, double*, double*)': pso.cpp:(.text+0xeb): undefined reference to rtInf' pso.cpp:(.text+0x12b): undefined reference to @987654326 @Sphere(double const*)' pso.cpp:(.text+0x32e): 未定义引用 c_rand(double*)' pso.cpp:(.text+0x339): undefined reference to c_rand(double*)' pso.cpp:(.text+0x864): 未定义引用 `Sphere(double const *)' collect2: ld 返回 1 个退出状态
  • 您可能需要添加库,例如在你的g++ 命令中最后一个*.cpp 文件之后的一些-lpso。您应该了解更多关于如何使用g++ 的信息。 g++ 的参数顺序很重要。并且使用-Wall -g 应该会有所帮助。最后,学习如何使用GNU make - 因为你有几个源文件......
  • @BlueBit:请注意b_rand(或c_rand)不是standard C++ 函数。可能某些标头声明了它,而某些库提供了它。你只知道哪个,我们猜不出来(可能是一些 Matlab 的东西????)
  • 亲爱的朋友们,我的问题解决了!我只是将所有*.cpp 文件(函数)调用到主程序中。你想过这样的呼唤吗?这很常见吗?还是应该调用*.h?但是,对于我调用*.cpp 的程序来说,程序就足够了。 :-)
  • @BlueBit - 这很常见,但它是错误的。 C++ 支持单独编译:每个源文件独立存在,因此您只需重新编译更改的文件。当您将所有内容放入单个文件时(这是#includeing 所有源文件的效果),您每次都重新编译所有内容。虽然这对于小型项目来说没什么大不了的,但对于大型项目来说,这会让一切变得更慢、更难理解。
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2013-06-01
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多