I'm using c++ 14. Why isn't googletest able to pick up the curl_client class object pointer? Did I initialize it correctly in CurlClientTest?
Testing code:
#include "../src/include/CurlClient.h"
#include <gtest/gtest.h>
#include <string>
class CurlClientTest : testing::Test {
public:
SimpleCURLClient::CurlClient *curl_client;
virtual void SetUp() {
curl_client = new SimpleCURLClient::CurlClient(test_url);
}
virtual void TearDown() {
delete curl_client;
}
private:
std::string test_url = "http://postman-echo.com/get?foo1=bar1&foo2=bar2";
};
TEST(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl << "\n";
}
code for CurlClient.h:
#include <curl/curl.h>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#ifndef UTILS_CURLCLIENT_H
#define UTILS_CURLCLIENT_H
namespace SimpleCURLClient {
class CurlClient {
public:
CurlClient(std::string remote_url, int ip_protocol = 1, int timeout = 10,
bool follow_redirects = 1);
~CurlClient();
void setCurlUrl(std::string &new_url);
std::string getCurlUrl();
void setOption(CURLoption curl_option_command, long curl_option_value);
void setOption(CURLoption curl_option_command, std::string curl_option_value);
void setHeader(std::vector<std::string> &header_list);
std::pair<CURLcode, std::string> makeRequest();
std::pair<CURLcode, std::string> makeRequest(std::string &post_params);
std::pair<CURLcode, std::string> sendGETRequest();
std::pair<CURLcode, std::string> sendPOSTRequest(std::string &post_params);
std::pair<CURLcode, std::string> sendDELETERequest(std::string &post_params);
private:
std::string m_curl_url;
CURL *m_curl;
struct curl_slist *m_curl_header_list;
};
} // namespace SimpleCURLClient
#endif // UTILS_CURLCLIENT_H
Error:
Build FAILED.
"E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj" (default target) (1) ->
(ClCompile target) ->
E:\somepath\simple_curl_cpp\test\CurlClientTest.cc(21): error C2065: 'curl_client': undeclared identifier [E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj]
E:\somepath\simple_curl_cpp\test\CurlClientTest.cc(21): error C2227: left of '->getCurlUrl' must point to class/struct/union/generic type [E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj]
ANSWER (GIVEN BY Chris Olsen in comments) :
We have to use TEST_F and NOT TEST. Also change CurlClientTest to public. The below code for the test works.
#include "../src/include/CurlClient.h"
#include <gtest/gtest.h>
#include <string>
class CurlClientTest : public testing::Test {
public:
SimpleCURLClient::CurlClient *curl_client;
virtual void SetUp() {
curl_client = new SimpleCURLClient::CurlClient(test_url);
}
virtual void TearDown() {
delete curl_client;
}
private:
std::string test_url = "http://postman-echo.com/get?foo1=bar1&foo2=bar2";
};
TEST_F(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl() << "\n";
}
Tests using fixtures require use of the TEST_F macro. See Test Fixtures in the Google Test Primer for more info.
TEST_F(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl << "\n";
}
Related
I've been trying to compile my project and I've encountered some problems when trying so. The error in particular that appears is:
[build] /usr/bin/ld: CMakeFiles/robot_control.dir/main.cpp.o:(.data.rel.ro._ZTVN4comm15cameraInterfaceE[_ZTVN4comm15cameraInterfaceE]+0x10): undefined reference to `comm::Interface<cv::Mat>::callbackMsg()'
My project is organized right now as it follows:
-${HOME_WORKSPACE}
|-main.cpp
|-src
|-communication.cpp
|-communication.hpp
The header file (communication.hpp) is:
#include <opencv2/opencv.hpp>
#include <gazebo/gazebo_client.hh>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/transport/transport.hh>
#include <algorithm>
#ifndef COMM_GUARD
#define COMM_GUARD
namespace comm
{
struct lidarMsg
{
float angle_min, angle_increment, range_min, range_max;
int nranges, nintensities;
std::vector<int> ranges;
};
template <typename T>
class Interface
{
public:
Interface() : received{false} {};
virtual void callbackMsg();
bool receptionAccomplished()
{
return this -> received;
}
T checkReceived()
{
return this -> elementReceived;
}
protected:
bool received;
T elementReceived;
};
class cameraInterface : public Interface<cv::Mat>
{
public:
void callbackMsg(ConstImageStampedPtr &msg);
};
class lidarInterface : public Interface<lidarMsg>
{
public:
void callbackMsg(ConstLaserScanStampedPtr &msg);
};
}
#endif
The source file (communication.cpp) is:
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
#include "communication.hpp"
#ifndef COMM_CPP_GUARD
#define COMM_CPP_GUARD
namespace comm
{
void cameraInterface::callbackMsg(ConstImageStampedPtr &msg)
{
std::size_t width = msg->image().width();
std::size_t height = msg->image().height();
const char *data = msg->image().data().c_str();
cv::Mat im(int(height), int(width), CV_8UC3, const_cast<char *>(data));
im = im.clone();
cv::cvtColor(im, im, cv::COLOR_RGB2BGR);
this->elementReceived = im;
received = true;
}
void lidarInterface::callbackMsg(ConstLaserScanStampedPtr &msg) {
this->elementReceived.angle_min = float(msg->scan().angle_min());
this->elementReceived.angle_increment = float(msg->scan().angle_step());
this->elementReceived.range_min = float(msg->scan().range_min());
this->elementReceived.range_max = float(msg->scan().range_max());
this->elementReceived.nranges = msg->scan().ranges_size();
this->elementReceived.nintensities = msg->scan().intensities_size();
for (int i = 0; i < this->elementReceived.nranges; i++)
{
if (this->elementReceived.ranges.size() <= i)
{
this->elementReceived.ranges.push_back(std::min(float(msg->scan().ranges(i)), this->elementReceived.range_max));
}
else
{
this->elementReceived.ranges[i] = std::min(float(msg->scan().ranges(i)), this->elementReceived.range_max);
}
}
}
}
#endif
The main file(main.cpp) includes the following header:
#include <gazebo/gazebo_client.hh>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/transport/transport.hh>
#include <opencv2/opencv.hpp>
#include <opencv2/calib3d.hpp>
#include <iostream>
#include <stdlib.h>
#include "src/communication.hpp"
I included the part of the #ifndef /#define /#endif since it is a solution that I found to this kind of problem in other problem. I've been toggling the CMakeLists.txt file but still no solution that could solve this error.
You can't do this:
virtual void callbackMsg();
You have to actually provide the implementation for all template methods within the .h file.
I have a dll with lib.h:
#pragma once
#ifdef EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
extern "C" API void test1(std::vector<ValueType*>* functions);
and lib.cpp:
#include "pch.h"
#include <iostream>
#include <vector>
#include "ValueType.h"
#include "NumberValue.h"
#include "TestLib.h"
void test1(std::vector<ValueType*>* functions) {
functions->push_back(new NumberValue(123321));
And main file, that uses this dll is:
#include <iostream>
#include <vector>
#include <Windows.h>
#include "ValueType.h"
using namespace std;
typedef void (__cdecl* importedInitFunction)(std::vector<ValueType*>*);
importedInitFunction test1F;
std::vector<ValueType*> values;
int main() {
while (1) {
HMODULE lib = LoadLibrary("DllTest1.dll");
test1F = (importedInitFunction)GetProcAddress(lib, "test1");
test1F(&values);
FreeLibrary(lib);
std::cout << values.at(0)->asString();
system("pause");
}
return 0;
}
When I'm trying to compile my code, I catch an error because values.at(0) is removed.
How to prevent deleting my variable when calling FreeLibrary(lib) ? or
How to implement alternative way ?
Another classes that used:
ValueType.h:
#pragma once
#include <string>
class ValueType {
public:
virtual double asDouble() { return 999; }
virtual std::string asString() { return ""; }
};
NumberValue.h:
#pragma once
#include <string>
#include "ValueType.h"
class NumberValue : public ValueType {
public:
double m_value;
NumberValue(double value) : m_value(value) {}
virtual double asDouble() {
return m_value;
}
virtual std::string asString() {
return std::to_string(m_value);
}
};
I've looked around, and I can't quite figure out where I'm going wrong, as I seem to be following the correct convention when using interfaces, but perhaps I'm overlooking something. The exact error I'm getting is:
undefined reference to `vtable for Icommand'
I've only just begun to seperate my classes and class declarations into separate header files, so perhaps I'm missing a preprocessor directive somewhere.
main.cpp:
#include <iostream>
#include <string>
#include <cstdlib>
#include "Icommand.h"
#include "Command.h"
using namespace std;
void pause();
int main(){
Icommand *run = new Command("TEST");
cout << run->getCommand() << endl;
delete run;
pause();
}
void pause(){
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
cin.get();
}
Icommand.h:
#ifndef ICOMMAND_H
#define ICOMMAND_H
#include <string>
#include <vector>
class Icommand
{
private:
public:
Icommand(){}
virtual ~Icommand(){}
virtual bool run(std::string object1) = 0;
virtual bool run(std::string object1, std::string object2) = 0;
virtual std::string getCommand() const;
};
#endif // ICOMMAND_H
Command.h:
#ifndef COMMAND_H
#define COMMAND_H
#include <string>
#include <vector>
#include "Icommand.h"
class Command : public Icommand {
private:
std::string command;
std::vector<std::string> synonymns;
Command(); // private so class much be instantiated with a command
public:
Command(std::string command) : command(command){}
~Command(){}
bool run(std::string object1);
bool run(std::string object1, std::string object2);
std::string getCommand() const;
};
#endif // COMMAND_H
Command.cpp:
#include <string>
#include <vector>
#include "Command.h"
bool Command::run(std::string object1){
return false;
}
bool Command::run(std::string object1, std::string object2){
return false;
}
std::string Command::getCommand() const {return command;}
In Icommand.h, replace
virtual std::string getCommand() const;
with
virtual std::string getCommand() const = 0;
to make it pure virtual. Then the compiler can generate a vtable for Icommand. Alternatively, implement Icommand::getCommand.
I am attempting to make part of a program that uses a bank account class as the base class and checking and savings as the derived classes. I have been trying to set up the basic framework before I do any fancy data handling and I've followed some tutorials to get a better understanding of classes and inheritance.
I have looked for answers but the answers I have found don't seem to be my problem but I might just need another set of eyes on my code.
the compiler errors:
In function main':
badriver.cpp:20: undefined reference toChecking::getAccount()'
badriver.cpp:23: undefined reference to Checking::setAccount(int)'
badriver.cpp:24: undefined reference toSavings::setAccount(int)'
badriver.cpp:26: undefined reference to `Checking::getAccount()'
badriver.cpp
#include "BankAccount.cpp"
#include "Checking.cpp"
#include "Savings.cpp"
#include <string>
#include <iostream>
using namespace std;
int main(){
Checking c;
Savings s;
cout << "Checking: " << c.getAccount() << " - Type: " << c.getType() << endl;
cout << "Savings: " << s.getAccount() << " - Type: " << s.getType() << endl;
c.setAccount(9);
s.setAccount(15);
cout << "New Checking: " << c.getAccount() << endl;
cout << "New Savings: " << s.getAccount() << endl;
return 0;
}
BankAccount.h
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <string>
using std::string;
using std::ostream;
using std::istream;
class BankAccount{
private:
int myAccount;
const char* color;
public:
// default constructor
BankAccount();
BankAccount(int account);
virtual ~BankAccount();
virtual void setAccount(int)=0;
int getAccount();
//
// void setSAccount(int);
// int getSAccount();
//
virtual const char* getColor();
virtual const char* getType() = 0;
//virtual const char* getCType() = 0;
protected:
void setColor(const char*);
};
#endif // BANKACCOUNT_H
BankAccount.cpp
#include "BankAccount.h"
#include "Checking.h"
#include "Savings.h"
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
// default constructor
BankAccount::BankAccount(){
account = 1;
}
BankAccount::~BankAccount(){}
// void BankAccount::setAccount(int account){
// myAccount = account;
// }
int BankAccount::getAccount(){
return myAccount ;
}
BankAccount::BankAccount(int account){
myAccount = account;
}
const char* BankAccount::getColor(){
return color;
}
void BankAccount::setColor(const char* c){
color = c;
}
Checking.h
#ifndef CHECKING_H
#define CHECKING_H
#include "BankAccount.h"
#include <string>
using std::string;
using std::ostream;
using std::istream;
class Checking : public BankAccount{
private:
const char* type;
public:
Checking();
virtual ~Checking();
void setAccount(int account);
virtual const char* getType();
void setChecking(int);
int getChecking();
};
#endif //CHECKING_H
Checking.cpp
#include "Checking.h"
#include <string>
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
Checking::Checking() : BankAccount(1), type("Checking"){}
Checking::~Checking(){}
BankAccount::~BankAccount(){}
void BankAccount::setAccount(int account){
myAccount = account;
}
const char* Checking::getType(){
return type;
}
Savings.h
#ifndef SAVINGS_H
#define SAVINGS_H
#include "BankAccount.h"
#include <string>
using std::string;
using std::ostream;
using std::istream;
class Savings: public BankAccount{
private:
const char* type;
public:
Savings();
virtual ~Savings();
void setAccount(int account);
virtual const char* getType();
void setSavings(int);
int getSavings();
};
#endif // SAVINGS_H
Savings.cpp
#include "Savings.h"
#include <string>
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
Savings::Savings() : BankAccount(2), type("Savings"){}
Savings::~Savings(){}
BankAccount::~BankAccount(){}
void BankAccount::setAccount(int account){
myAccount = account;
}
const char* Savings::getType(){
return type;
}
Thanks for any help pointing me in the right direction.
Checking.cpp and Savings.cpp contain:
BankAccount::~BankAccount(){}
void BankAccount::setAccount(int account){
myAccount = account;
}
This causes undefined behaviour because you defined those functions in multiple files. You need to delete those lines from Checking.cpp and Savings.cpp, and instead put in definitions for the functions which are listed as being missing in the compiler output:
void Checking::setAccount(int account){
// code here
}
etc.
I've got a third party library named person.lib and its header person.h. This is my actual project structure and it compiles and runs perfectly.
Actual Structure:
main.cpp
#include <iostream>
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
using namespace person;
using namespace std;
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
I want to refactor my code by dividing the declaration of my Client class from its definition and create client.h and client.cpp. PAY ATTENTION: sayHello() and onMessage(const * char const) are functions of the person library.
Refactored Structure:
main.cpp
#include <iostream>
#include "client.h"
using namespace person;
using namespace std;
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
client.cpp
#include "client.h"
using namespace person;
using namespace std;
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
client.h
#ifndef CLIENT_H
#define CLIENT_H
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
#endif
As you can see, I've simply created a client.h in which there's the inclusion of the base class person.h, then I've created client.cpp in which there's the inclusion of client.h and the definitions of its functions. Now, the compilation gives me these errors:
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2440: 'inizialization': unable to convert from 'Client *' to 'person::impl::Person *' main.cpp 15 1 Test
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2039: 'setName': is not a member of 'Client' client.cpp 8 1 Test
error C3861: 'sendMessage': identifier not found client.cpp 34 1 Test
It's a merely cut© refactoring but it doesn't work and I really don't understand WHY! What's the solution and why it gives me these errors? Is there something about C++ structure that I'm missing?
Here's a dog-n-bird implementation (ruff ruff, cheep cheep)
cLawyer is defined and implemented in main.cpp, while cPerson and cClient are defined in their own header files, implemented in their own cpp file.
A better approach would store the name of the class. Then, one wouldn't need to overload the speak method - one could simply set the className in each derived copy. But that would have provided in my estimates, a less useful example for you.
main.cpp
#include <cstdio>
#include "cClient.h"
class cLawyer : public cPerson
{
public:
cLawyer() : cPerson() {}
~cLawyer() {}
void talk(char *sayWhat){printf("cLawyer says: '%s'\n", sayWhat);}
};
int main()
{
cPerson newPerson;
cClient newClient;
cLawyer newLawyer;
newPerson.talk("Hello world!");
newClient.talk("Hello world!");
newLawyer.talk("Hello $$$");
return 0;
}
cPerson.h
#ifndef cPerson_h_
#define cPerson_h_
class cPerson
{
public:
cPerson();
virtual ~cPerson();
virtual void talk(char *sayWhat);
protected:
private:
};
#endif // cPerson_h_
cPerson.cpp
#include "cPerson.h"
#include <cstdio>
cPerson::cPerson()
{
//ctor
}
cPerson::~cPerson()
{
//dtor
}
void cPerson::talk(char *sayWhat)
{
printf("cPerson says: '%s'\n",sayWhat);
}
cClient.h
#ifndef cClient_h_
#define cClient_h_
#include "cPerson.h"
class cClient : public cPerson
{
public:
cClient();
virtual ~cClient();
void talk(char *sayWhat);
protected:
private:
};
#endif // cClient_h_
cClient.cpp
#include "cClient.h"
#include <cstdio>
cClient::cClient()
{
//ctor
}
cClient::~cClient()
{
//dtor
}
Output
cPerson says: 'Hello world!'
cClient says: 'Hello world!'
cLawyer says: 'Hello $$$'
Suggestions noted above:
//In the cPerson class, a var
char *m_className;
//In the cPerson::cPerson constructer, set the var
m_className = "cPerson";
//Re-jig the cPerson::speak method
void cPerson::speak(char *sayWhat)
{
printf("%s says: '%s'\n", m_className, sayWhat);
}
// EDIT: *** remove the speak methods from the cClient and cLawyer classes ***
//Initialize the clas name apporpriately in derived classes
//cClient::cClient
m_className = "cClient";
//Initialize the clas name apporpriately in derived classes
//cLaywer::cLaywer
m_className = "cLawyer";
You are declaring the class Client twice - once in the .h file and once in .cpp. You only need to declare it in the .h file.
You also need to put the using namespace person; to the .h file.
If class Person is in namcespace person, use the person::Person to access it.
The client.cpp must contain definitions only!
I think for the linker the class Client defined in client.h and class Client defined in client.cpp are different classes, thus it cannot find the implementation of Client::Client(). I purpose to remove the declaration of class Client from the client.cpp and leave there only definitions of functions:
// client.cpp
#include <time.h>
#include <ctype.h>
#include <string>
#include "client.h"
using namespace std;
Client::Client()
{
//DO STUFF
}
void Client::onMessage(const char * const message)
{
//DO STUFF
}
void Client::gen_random(char *s, const int len) {
//DO STUFF
}