Mar 4, 2019 at 2:19am Mar 4, 2019 at 2:19am UTC
I am attempting to use a std::function that SHOULD be in a library, but it does not seem to work.
I then dumbed it down to just attempting to link 2 object files, but it still does not work.
Here are the details:
my_func.cpp
1 2 3 4 5 6 7 8 9
#include <functional>
#include <string>
const std::function<std::string(const char *)> use_std_function = [](const char * str) { return std::string(str); };
const std::string use_function(const char * str)
{
return std::string(str);
}
test.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <string>
#include <functional>
#include <iostream>
const extern std::function<std::string(const char *)> use_std_function;
const extern std::string use_function(const char *);
int main(int argc, char ** argv)
{
const char * input = "Hello, world!" ;
{
std::string output = (use_function)(input);
if (output != input)
std::cerr << "Output does not equal input after use_function" ;
}
{
std::string output = (use_std_function)(input);
if (output != input)
std::cerr << "Output does not equal input after use_std_function" ;
}
return 0;
}
Command line:
Results:
1 2 3
/usr/bin/ld: /tmp/ccc0sxWt.o: in function `main':
test.cpp:(.text+0x7e): undefined reference to `use_std_function[abi:cxx11]'
collect2: error: ld returned 1 exit status
It seems use_function is working, as if I comment out use_std_function it compiles and runs. But I am not sure what I am doing wrong with the std::function. Any help is appreciated.
Additional note: #including my_func.cpp as if it were a header works, but is not what I am after.
Last edited on Mar 4, 2019 at 2:25am Mar 4, 2019 at 2:25am UTC
Mar 4, 2019 at 3:26am Mar 4, 2019 at 3:26am UTC
The problem is with the initial "const". Get rid of it and it works.
Mar 4, 2019 at 12:24pm Mar 4, 2019 at 12:24pm UTC
Thank you!
I will read up on extern. I always had the impression it was nothing more than a linker hint, and normally not required.