Reputation: 33864
I am using someone elses function that takes:
optimise(std::vector<double> &input)
It edits the input.
How should I pass a vector to this, I have tried:
std::vector<double> input;
input.push_back('several points');
optimise(input);
This has a linker error saying:
undefined reference to optimise(std::vector<double, std::allocator<double> >&)
If i try this:
std::vector<double> &input;
input.push_back('several points');
optimise(input);
Then there is a compile error:
'input' declared as reference but not initialised
How do I initialise a reference to the vector or am I doing something completely wrong. EDIT:
I wasn't linking a library correctly in my CMakeLists. Thanks for everyone's help, i wish i could mark you all as correct.
Upvotes: 2
Views: 1259
Reputation: 60858
The first attempt appears to fail due to some linker error. You must ensure that the function you call is actually available to the linker, either in some kind of library, or as a separate translation unit (source file), or similar. Just including the header is enough for the compiler, but won't help the linker.
'input' declared as reference but not initialised
This makes sense: a reference is always a reference to some object which exists elsewhere. So you cannot use a reference without first telling it what to refer to. The most common case is using references as function arguments. Usually the object would be a normal non-reference object in the scope of the caller, and passed to the callee via reference to avoid copying. In that respect, your first attempt is correct.
Upvotes: 1
Reputation: 726509
Your first way of passing the vector
is correct. The compiler recognizes that the vector is passed to the function by reference from the signature in the header, makes a reference to your vector, and passes it to the function. The fact that you see linker errors tells you that the compile stage completed successfully.
The linker error is there because you are failing to include the library where the optimise
function is implemented.
Upvotes: 2