Nogurenn
Nogurenn

Reputation: 878

"Candidate function not viable" from g++/gcc compiler. What is wrong here?

I'm trying to compile my main.cpp, but I keep getting this error for two hours now. The issue here is to pass a function as a parameter but I think I'm doing something wrong. The compiler says it cannot find the function, but I included "newt_rhap(params)" in the "functions.h" already.

I did the returnType (*functionName)(paramType), but I may have skipped something here. The code of my friends doesn't need the recently mentioned syntax. What is wrong here?

I tried using both -std=c++11 and -std=c++98. The gcc/g++ compiler came from my Xcode command line tools.

g++ (or gcc) -std=c++98(or 11) main.cpp -o main.out

There was no difference in error.

**error: no matching function for call to 'newt_rhap'**

./functions.h:5:8: note: candidate function not viable: no known conversion from 'double' to
      'double (*)(double)' for 1st argument

double newt_rhap(double deriv(double), double eq(double), double guess);

Here is the code.

// main.cpp
#include <cmath>
#include <cstdlib>
#include <iostream>
#include "functions.h"

using namespace std;


// function declarations
// =============
// void test(double d);
// =============

int main(int argc, char const *argv[])
{
    //
    // stuff here excluded for brevity
    //

    // =============
    do
    {
        // line with error
        guess = newt_rhap(eq1(guess),d1(guess),guess);

        // more brevity

    } while(nSig <= min_nSig);
    // =============

    cout << "Root found: " << guess << endl;

    return 0;
}

Then functions.h and functions.cpp, respectively

// functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

// ===========
double newt_rhap(double deriv(double), double eq(double), double guess);
// ===========


// ===========
double eq1(double x);
double d1(double x);
// ===========


#endif

// functions.cpp
#include <cmath>
#include "functions.h"

using namespace std;

// ===========
double newt_rhap(double (*eq)(double ) , double (*deriv)(double ), double guess)
{
    return guess - (eq(guess)/deriv(guess));
}
// ===========

// ===========
double eq1(double x)
{
    return exp(-x) - x;
}

double d1(double x)
{
    return -exp(-x) - 1;
}

Upvotes: 9

Views: 31555

Answers (2)

Patrick Sanan
Patrick Sanan

Reputation: 2485

The signature of your function prototype in functions.h does not match the signature of the function you implement in functions.cpp.

Upvotes: 4

Sam Cristall
Sam Cristall

Reputation: 4387

Instead of:

guess = newt_rhap(eq1(guess),d1(guess),guess);

try:

guess = newt_rhap(eq1, d1, guess);

The function takes two functions and a guess as arguments. By passing eq1(guess) you are passing a double, not a function (the evaluated result of eq1 with an argument of guess)

Upvotes: 7

Related Questions