Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference C++

I'm trying to compile my first legit program that I'm converting from Java (I ran a test hello world type program to check my compiler and it works). There are three files:

main.cpp

#include <iostream>
#include "skewNormal.h"

using namespace std;

double getSkewNormal(double, double);

int main(int argc, char **argv) {
    cout << getSkewNormal(10.0, 0.5) << endl;
}

skewNormal.cpp

#define _USE_MATH_DEFINES
#include <iostream>
#include <math.h>

using namespace std;

#include <skewNormal.h>

double SkewNormalEvalutatable::evaluate(double x)
{
    return 1 / sqrt(2 * M_PI) * pow(M_E, -x * x / 2);
}

SkewNormalEvalutatable::SkewNormalEvalutatable()
{
}

double sum (double start, double stop,
                               double stepSize,
                               Evaluatable evalObj)
{
  double sum = 0.0, current = start;
  while (current <= stop) {
    sum += evalObj.evaluate(current);
    current += stepSize;
  }
  return(sum);
}

double integrate (double start, double stop,
                                     int numSteps,
                                     Evaluatable evalObj)
{
  double stepSize = (stop - start) / (double)numSteps;
  start = start + stepSize / 2.0;
  return (stepSize * sum(start, stop, stepSize, evalObj));
}

double getSkewNormal(double skewValue, double x)
{
  SkewNormalEvalutatable e;
  return 2 / sqrt(2 * M_PI) * pow(M_E, -x * x / 2) * integrate(-1000, skewValue * x, 10000, e);
}

skewNormal.h

#ifndef SKEWNORMAL_H_INCLUDED
#define SKEWNORMAL_H_INCLUDED

class Evaluatable {
public:
  virtual double evaluate(double x);
};

class SkewNormalEvalutatable : Evaluatable{
public:
  SkewNormalEvalutatable();
  double evaluate(double x);
};

double getSkewNormal(double skewValue, double x);

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

double sum (double start, double stop, double stepSize, Evaluatable evalObj);

#endif // SKEWNORMAL_H_INCLUDED

Compiling yielded the following error:

main.cpp:9: undefined reference to `getSkewNormal(double, double)'

I'm using Code::Blocks on Ubuntu 10.10.

like image 781
Ryan Amos Avatar asked Jun 08 '11 20:06

Ryan Amos


2 Answers

You may be compiling skewNormal.cpp to a .o file, but you're not including it when you compile main.cpp.

like image 156
Mark Ransom Avatar answered Oct 17 '22 13:10

Mark Ransom


Not sure if this is the problem, but it appears you're prototyping the function twice.

The double getSkewNormal(double skewValue, double x); line need only be in the header, not in main.cpp as well (since main.cpp includes skewNormal.h). Having it appear twice in a prototype form seems likely to confuse the compiler. You only need it to be visible to the code once, and usually that should be in a header (not a code file).

Try removing that line from main.cpp and recompile. :)

like image 37
ssube Avatar answered Oct 17 '22 12:10

ssube