Search code examples
c++11g++swigld

ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1


I am converting a C++ code to python code using SWIG on MAC OS. I used SWIG before but now I have some bug that I did not succeed to manage. So for using SWIG, I created a file RBergomi.i and applied the following commands

swig -c++ -python RBergomi.i

g++ -O2 -fPIC -c -std=c++11 RBergomi_wrap.cxx -I/Users/.../anaconda/include/python2.7

g++ -std=c++11 -shared RBergomi_wrap.o -o RBergomi.so

but I get this error

"ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 "

I tried to look for the issue and it seems that the error is coming from using std::accumulate, which to use I need to call "numeric" header and then I have the issue. if I remove the header "numeric" I do not have the previous error anymore but accumulate is not known. Below the code of my RBergomi.cpp file

#include "rBergomi.h"

double updatePayoff_cholesky(Vector& Wtilde, const Vector& W1,
    Vector& v, double eta, double H, double rho, double xi,
    double T, double K, int N){
double dt = T / N;
double sdt = sqrt(dt);
scaleVector(Wtilde, pow(T, H)); // scale Wtilde for time T
compute_V(v, Wtilde, H, eta, xi, dt); // compute instantaneous variance v
double Ivdt = intVdt(v, dt);
double IsvdW = intRootVdW(v, W1, sdt);
double BS_vol = sqrt((1.0 - rho * rho) * Ivdt);
double BS_spot = exp(-0.5 * rho * rho * Ivdt + rho * IsvdW);
return BS_call_price(BS_spot, K, 1.0, BS_vol);}
void compute_V(Vector& v, const Vector& Wtilde, double H, double eta, double xi,
    double dt) {
v[0] = xi;
for (int i = 1; i < v.size(); ++i)
    v[i] = xi
            * exp(
                    eta * Wtilde[i - 1]
                            - 0.5 * eta * eta * pow(i * dt, 2 * H));}

double intVdt(const Vector & v, double dt) {
return dt * std::accumulate(v.begin(), v.end(), 0.0);}
double intRootVdW(const Vector & v, const Vector & W1, double sdt) {
double IsvdW = 0.0;
for (size_t i = 0; i < v.size(); ++i)
    IsvdW += sqrt(v[i]) * sdt * W1[i];
return IsvdW;}
double pnorm(double value) {
return 0.5 * erfc(-value * M_SQRT1_2); }
double BS_call_price(double S0, double K, double tau, double sigma, double r) {
double d1 = (log(S0 / K) + (r + 0.5 * sigma * sigma) * tau)
        / (sigma * sqrt(tau));
double d2 = d1 - sigma * sqrt(tau);
return pnorm(d1) * S0 - pnorm(d2) * K * exp(-r * tau);}

Solution

  • I solved the issue by using -lpython -dynamiclib to address the linking issue, giving:

    swig -c++ -python RBergomi.i
    
    g++ -O2 -fPIC -c RBergomi.cpp
    
    g++ -O2 -fPIC -c  RBergomi_wrap.cxx -I/Users/hammouc/anaconda/include/python2.7
    
    g++ -lpython -dynamiclib RBergomi.o RBergomi_wrap.o -o _RBergomi.so