Passing function as parameter --- Linker error?

Hello !

I want to pass a function as parameter in another file.h and it leads to a linker error and I don’t understand why ? any helps !

here’s a part of the code

in ofApp

#include "NeuralNetwork.h"
//...
 NeuralNetwork *nn = new NeuralNetwork(2,2,2);
 std::vector< float > input = {1, 0};
 std::vector< float > targets = {1, 0};
 nn->train(input, targets);

in NeuralNetwork.h
I declare/define outside the class the function sigmoid() that I want to pass as param …

#include "Matrix.h"

float sigmoid(float x){
        return 1. / (1. + exp(-x));
}
//--------------------------------------------------------------
class NeuralNetwork{
public:
//...
 void train(std::vector<float> inputs, std::vector<float> targets_vec){
        std::vector< float > outputs_vec = feedforward(inputs);
 }
// in the function feedforward() I try to pass the function sigmoid()...
 std::vector<float> feedforward(std::vector<float> input_vec){
        hidden->map(sigmoid); // hidden is a pointer to a Matrix object
}

then in Matrix.h, I try to use the function

class Matrix{
public:
//...
     void map( float (*func)(float) ){
        for(int i=0; i < rows_; i++) {
            for(int j=0; j < cols_; j++){
                float val = data_[i][j];
                data_[i][j] = func( val );
            }
        }
    }
};

Thank’s for your help !

what is your error output?
did you try renaming your void map to another name?

Here’s my error output…
I just try renaming the map function and it doesn’t works…

duplicate symbol ‘sigmoid(float)’ in:
/Users/guillaumesylvain/Library/Developer/Xcode/DerivedData/Perceptron-atozdyvpbchhfbeoqtstzeaiuaae/Build/Intermediates.noindex/Perceptron.build/Debug/Perceptron.build/Objects-normal/x86_64/main.o
/Users/guillaumesylvain/Library/Developer/Xcode/DerivedData/Perceptron-atozdyvpbchhfbeoqtstzeaiuaae/Build/Intermediates.noindex/Perceptron.build/Debug/Perceptron.build/Objects-normal/x86_64/ofApp.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

it is hard to see where the error is without seeing the entire code. it seems like you are including some .h file twice. Something related with main.cpp?

Anyway you can solve this by moving the function sigmoid to inside of class NeuralNetwork, or maybe declaring it as static? just guessing

1 Like

Thank’s dimitre !

Still not very clear for me why, but both moving the function inside of class NeuralNetwork and declaring it as static works…

yeah I think just moving to inside the class would be enough

1 Like

It sounds like you are missing a header guard in the h file causing it to be included more than once.