简体   繁体   中英

C++ Linker error in Xcode for a Static Method

I'm sure this is bone-headly simple but I just can't see it. I'm getting the following linker error in C++ Xcode.

Undefined symbols for architecture x86_64:
"Random::NextInt(int, int)", referenced from:
Helpers::MakeData(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int) in Helpers.o

Helpers::MakeData

#include "Helpers.h"
#include "Random.h"

void Helpers::MakeData(string dataFile, int numLines)
{
    vector<double> weights = { -0.1, 0.2, -0.3, 0.4, -0.5,
    0.6, -0.7, 0.8, -0.9, 1.0,
    -1.1, 1.2, -1.3, 1.4, -1.5,
    1.6, -1.7, 1.8, -1.9, 2.0,
    -0.5, 0.6, -0.7, 0.8, -0.9,
    1.5, -1.4, 1.3,
    -1.2, 1.1, -1.0,
    0.9, -0.8, 0.7,
    -0.6, 0.5, -0.4,
    0.3, -0.2, 0.1,
    0.1, -0.3, 0.6 };

    NeuralNetwork * nn = new NeuralNetwork(4, 5, 3);
    nn->SetWeights(weights);
    ofstream myFile;
    myFile.open(dataFile);
    for (int i = 0; i < numLines; ++i)
    {
        vector<double> inputs; 
        for (int j = 0; j < inputs.size(); ++j)
            inputs[j] = Random::NextInt(10, 1);

        vector<double> outputs = nn->ComputeOutputs(inputs);

        string color = "";
        int idx = Helpers::IndexOfLargest(outputs);
        if (idx == 0) { color = "red"; }
        else if (idx == 1) { color = "green"; }
        else if (idx == 2) { color = "blue"; }

        myFile << inputs[0] << " " << inputs[1] << " " << inputs[2] << " " << inputs[3] <<      " " << color;
    }
    myFile.close(); 
} // MakeData

Random.h

#ifndef __NeuralClassificationProgram__Random__
#define __NeuralClassificationProgram__Random__

#include <iostream>
class Random{

public:
    static double NextDouble();
    static int NextInt(int high, int low);
};

#endif /* defined(__NeuralClassificationProgram__Random__) */

Random.cpp

#include "Random.h"
#include <time.h>
#include <stdlib.h>

double NextDouble()
{
    double rnd;
    srand(static_cast<unsigned int>(time(NULL)));
    rnd = rand() % 1+0;
    return rnd;
}

int NextInt(int high, int low)
{
    int rnd;
    srand(static_cast<unsigned int>(time(NULL)));
    rnd = rand() % high + low;
    return rnd;
}

You did not include the class name qualifier in the implementation, so those "static methods" are being compiled as simple global functions.

For example, you have:

int NextInt(int high, int low)

But you need:

int Random::NextInt(int high, int low)

It's because you never defined Random::NextInt(int, int) , you defined NextInt(int, int) .

In other words, you forgot the class scope operator.
Try

int Random::NextInt(int high, int low)
{
    return rand() % high + low;
}

Oh, and don't call srand more than once in your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM