I have a file Cache.cpp that has a corresponding header file Cache.h and another NetFunctions.cpp that has a corresponding header file NetFunction.h.
I have a makefile that looks like this
all: net cache
g++ main.cpp ../obj/NetFunctions.o ../obj/Cache.o -o ../bin/main
net: NetFunctions.cpp
g++ -c NetFunctions.cpp -o ../obj/NetFunctions.o
cache: Cache.cpp net
g++ -c Cache.cpp ../obj/NetFunctions.o -o ../obj/Cache.o
Now NetFunctions.cpp has a function getNFHTML(string) defined there, which is used in Cache.cpp. I have checked the header files and they look fine with all the functions, declared there and header files properly included.
However, when I make, I get the following linker error
../obj/Cache.o: In function `Cache::getHTML(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
Cache.cpp:(.text+0x19ee): undefined reference to `getNFHTML(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
make: *** [test] Error 1***
Can someone help me with this? What is the problem?
I have also referred to this post C++ Linking error, but it was of no help to me.
Edit
Here is the code:
NetFunctions.h
#ifndef NET
#define NET 1
#include "commons.h"
bool serv_bind(struct addrinfo **servinfo, struct addrinfo **p, int *sockfd, int *yes);
void* get_in_addr(struct sockaddr *sa);
string getNFHTML(string website);
string saveHeaders(string);
//bool getNFHTML(string request, string last_modified, string *response);
extern bool useCache;
#endif
NetFunctions.cpp
#include "NetFunctions.h"
string getNFHTML(string request)
{
// a lot of code
}
Cache.cpp
#include "NetFunctions.h"
#include "Cache.h"
string Cache::getHTML(string request)
{
//some code
string response = getNFHTML(request);
//some code
}
I have stripped the files as they contained several hundred lines
This has nothing to do with the problem, but I put it in an answer so it will be better formated.
Your makefile doesn’t handle dependencies very well. Try this one instead:
For the
../bin/maintarget, the variable$^means to take all prerequisites, and$@is the target of the rule. This means you can add as many object files as you like, and all will be linked.For the compilation of the source to object files, the
$<variable is the first prerequisite. This will also make it easier to copy/paste the targets if you add more files.The rules also make sure that when you build
../bin/mainall files it depends on will be built properly.The first target,
all, will be the default if you runmakewithout specifying a target. It has been marked as a phony target, because it doesn’t produce a file calledall.Note that I’m basing this on GNU make, which is standard in almost all Linux distributions, and in Cygwin/MingW. If you use BSD make the variables might change.