Reputation: 2737
I am a C++ noob, fiddling with the following problem for some hours now. Hopefully, someone can enlighten me.
I had a cpp file with content like so:
test.cpp file content
#include <iostream>
#include <exception>
#include <stdlib.h>
#include <string.h>
using std::cin; using std::endl;
using std::string;
string foobar(string bar) {
return "foo" + bar;
}
int main(int argc, char* argv[])
{
string bar = "bar";
System::convCout << "Foobar: " << foobar(bar) << endl;
}
This one compiles and runs well. Now I'd like to put foobar into an external library:
mylib.h file content
string foobar(string bar);
mylib.cpp file content
#include <string.h>
using std::cin; using std::endl;
using std::string;
string foobar(string bar) {
return "foo" + bar;
}
test.cpp file content
#include <iostream>
#include <exception>
#include <stdlib.h>
#include "mylib.h"
int main(int argc, char* argv[])
{
string bar = "bar";
System::convCout << "Foobar: " << foobar(bar) << endl;
}
I adjusted my Makefile, so that test.cpp compiles and links mylib, but I always encounter the error:
test.cpp::8 undefined reference to `foobar(std::string)
How do I have to handle string arguments? My attempts seems to be completely wrong here.
Regards Felix
Upvotes: 0
Views: 157
Reputation: 227618
The C++ standard library type std::string
is in the header string
. To use it, you must include <string>
, not <string.h>
. Your mylib.h
should look something like
#ifndef MYLIB_H
#define MYLIB_H
#include <string>
std::string foobar(std::string bar);
#endif
and your mylib.cpp
should include it:
#include "mylib.h"
std::string foobar(std::string bar) {
return "foo" + bar;
}
Note that it may be unnecessary to pass bar
by value. Looking at your code, a const
reference might do.
Upvotes: 1