I try to write a simple function my_to_string()
in C++ that takes two iterators, first
and last
. I want the function to have a typical behavior: It shall iterate over [first,last)
and do something with the objects' data with only read access to them. I have the declaration for this function in one file stringformat.h
, its definition in the stringformat.cpp
, and I try to call it from another .cpp
file.
All files compile fine.
I use Eclipse CDT to build my project.
Now my problem is that I get the following linker error (straight copy-paste from Eclipse console, only home dir renamed for privacy reasons):
Invoking: Cross G++ Linker
g++ -o "agos2" ./agos/pairingfunctions/CantorPairingFunction.o ./agos/pairingfunctions/CantorTupleIncrementer.o ./agos/pairingfunctions/PairingFunction.o ./agos/machine/Instruction.o ./agos/machine/Machine.o ./agos/machine/MachineFactory.o ./agos/machine/Operation.o ./agos/machine/Program.o ./agos/goedelnumbering/multiplier/InstructionGoedel.o ./agos/goedelnumbering/multiplier/InstructionIncrementer.o ./agos/goedelnumbering/multiplier/MachineIncrementer.o ./agos/goedelnumbering/multiplier/OperationIncrementer.o ./agos/goedelnumbering/multiplier/ProgramIncrementer.o ./agos/BigIntegerLibrary/BigInteger.o ./agos/BigIntegerLibrary/BigIntegerAlgorithms.o ./agos/BigIntegerLibrary/BigIntegerUtils.o ./agos/BigIntegerLibrary/BigUnsigned.o ./agos/BigIntegerLibrary/BigUnsignedInABase.o ./agos/Agos.o ./agos/Int64ToInt64Function.o ./agos/stringformat.o ./agos.o
./agos/machine/Machine.o: In function `agos::Machine::toStringWithState() const':
/home/username/workspace-cpp/agos2/Debug/../agos/machine/Machine.cpp:280: undefined reference to `std::string agos::my_to_string<__gnu_cxx::__normal_iterator<long const*, std::vector<long, std::allocator<long> > > >(__gnu_cxx::__normal_iterator<long const*, std::vector<long, std::allocator<long> > >, __gnu_cxx::__normal_iterator<long const*, std::vector<long, std::allocator<long> > >)'
collect2: error: ld returned 1 exit status
make: *** [agos2] Error 1
Code here:
stringformat.h
//...
template<class InputIterator>
std::string my_to_string(InputIterator first, InputIterator last);
//...
stringformat.cpp
//...
template<class InputIterator>
string my_to_string(InputIterator first, InputIterator last) {
ostringstream oss;
if (last - first > 0) {
for (; first + 1 != last; ++first) {
oss << *first << ' ';
}
oss << *first;
}
return oss.str();
}
//...
code using the function:
#include "../stringformat.h"
//...
void my_use_case() {
vector<int64_t> const& v = ...;
string s;
s = my_to_string(v.begin(), v.end()); // Linker complains here; this is line 280
//...
}
In the linker command, the stringformat.o is included, so I think the function should get found. I've also positively checked that a stringformat.o file exists in my project folder.
I've also tried copy-pasting the function definition right before my_use_case()
. Then it compiles fine. No errors whatsoever. But this is not a nice solution.