a multiple definition error in c++
-
27-02-2021 - |
Question
I have 2 files, grabURL.cpp and grabURL.hpp. When I compile the both with gcc it gives me multiple definitions errors.
grabURL.cpp
#include "grabURL.hpp"
size_t buffer(void *ptr, size_t size, size_t nmemb, void *stream) {
int numbytes = size*nmemb;
char lastchar = *((char *) ptr + numbytes - 1);
*((char *) ptr + numbytes - 1) = '\0';
ret.append((char *)ptr);
ret.append(1,lastchar);
*((char *) ptr + numbytes - 1) = lastchar;
return size*nmemb;
}
void grabURL(std::string url, std::string *theRet){
curl_easy_setopt(curl,CURLOPT_URL,url.c_str());
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, buffer);
res = curl_easy_perform(curl);
*theRet = ret;
}
grabURL.hpp:
#ifndef CURLURLGRAB_HPP
#define CURLURLGRAB_HPP
#include <string>
#include <curl/curl.h>
CURL * curl;
CURLcode res;
std::string ret;
size_t buffer(void *ptr, size_t size, size_t nmemb, void *stream);
void grabURL(std::string url,std::string* theRet);
#endif
I have no idea what I am doing wrong, I thought I did the ifndef thing correctly. What exactly is wrong?
Solution
This definitions in your header file:
CURL * curl;
CURLcode res;
std::string ret;
get defined when you include the file from the cpp file, and pressumably some other translation unit (perhaps main.cpp?)
They don't look like something that should be in a header file, but if they do then you can declare them extern
within the header file and move the actual definitions to the cpp file.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow