0

I have a little static library "simpsonlib" which was built from one file "simpson.cpp". The library and a header file (simpson.hpp) are located in a sub-directory which is called "integrate". Now, I'd like to link the main.cpp file with the library, so I can use the function "simpsonIntegrator()" which declared in simpson.hpp and defined in simpson.cpp (now in the library archive):

main.cpp:

#include <iostream>
#include "integrator/simpson.hpp"

int main()
{
    auto f = [](double x){
        return x*x;
    };

    std::cout << simpsonIntegrator(f,0,5,20);
    return 0;
}

simpson.hpp

#ifndef SIMPSON_HPP
#define SIMPSON_HPP

template <class Function>
double simpsonIntegrator(Function&& f, double a, double b, int N);

#endif /*SIMPSON_HPP*/

simpson.cpp

#include "simpson.hpp"
#include <cassert>

template <class Function>
double simpsonIntegrator(Function&& f, double a, double b, int N){

    //some code

}

Now I'd like to link the main.cpp file with the static library to be able to use the function simpsonIntegrator.

First I have created the static library with:

c++ -c simpson.o simpson.cpp 
ar rcs libsimpson.a simpson.o

and then tried linking to it using:

c++ main.cpp -L./integrator -lsimpson

which results in an error in simpson.hpp:

error: ‘double simpsonIntegrator(Function&&, double, double, int) [with Function = main()::<lambda(double)>&]’, declared using local type ‘main()::<lambda(double)>’, is used but never defined

What have I done wrong?
Thanks a lot for your inputs!

Samuel
  • 11
  • 1
  • 1
    [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) may be appropriate. – Retired Ninja Feb 10 '23 at 14:08
  • `simpson.cpp` is your bug. You need to implement your template in the header file. – drescherjm Feb 10 '23 at 14:08
  • You are going to have to change your library to a *header only library*. Templates should usually be defined in header files. – john Feb 10 '23 at 14:10

0 Answers0