GPS App compile errors - c++

I am working on a GPS application on the Raspberry pi. I have just installed GPSD by running sudo apt-get install gpsd gpsd-clients. I do get data from my GPS module when I run sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock. My issue resides when I try to make my own GPS app. I have installed libgps-dev
When I try to compile my app I get two errors : undefined reference to gpsmm::~gpsmm() and undefined reference to gpsmm::gps_inner_open(char const*, char const*)
My Main Method:
#include <libgpsmm.h>
int main(int argc, char *argv[])
{
gpsmm gps_rec("localhost", DEFAULT_GPSD_PORT);
return 0;
}
libgpsmm.h:
#ifndef _GPSD_GPSMM_H_
#define _GPSD_GPSMM_H_
/*
* Copyright (C) 2005 Alfredo Pironti
*
* This software is distributed under a BSD-style license. See the
* file "COPYING" in the toop-level directory of the distribution for details.
*
*/
#include <sys/types.h>
#include "gps.h" //the C library we are going to wrap
#ifndef USE_QT
class gpsmm {
#else
#include <QtCore/qglobal.h>
#if defined(LIBQGPSMM_LIBRARY)
# define LIBQGPSMMSHARED_EXPORT Q_DECL_EXPORT
#else
# define LIBQGPSMMSHARED_EXPORT Q_DECL_IMPORT
#endif
class LIBQGPSMMSHARED_EXPORT gpsmm {
#endif
public:
// cppcheck-suppress uninitVar
gpsmm(const char *host, const char *port) : to_user(0) {
gps_inner_open(host, port);
}
#ifdef __UNUSED__
// cppcheck-suppress uninitVar
gpsmm(void) : to_user(0)
{
gps_inner_open("localhost", DEFAULT_GPSD_PORT);
}
#endif
virtual ~gpsmm();
struct gps_data_t* send(const char *request); //put a command to gpsd and return the updated struct
struct gps_data_t* stream(int); //set watcher and policy flags
struct gps_data_t* read(void); //block until gpsd returns new data, then return the updated struct
const char *data(void); // return the client data buffer
bool waiting(int); // blocking check for data waiting
void clear_fix(void);
void enable_debug(int, FILE*);
private:
struct gps_data_t *to_user; //we return the user a copy of the internal structure. This way she can modify it without
//integrity loss for the entire class
struct gps_data_t* gps_inner_open(const char *host, const char *port);
struct gps_data_t _gps_state;
struct gps_data_t * gps_state() { return &_gps_state; }
struct gps_data_t* backup(void) { *to_user = *gps_state(); return to_user; }; //return the backup copy
};
#endif // _GPSD_GPSMM_H_
If anyone can help me figure out my problem, I would be grateful.

The problem is that you are most likely not linking your source code with the library.

You should pass it to your g++ with
g++ -o output sourceFileThatImplementsLibGPS.cpp -lgps

Related

G++ - Undefined Reference to member function that is defined

I am currently working on a virtual run time environment program that is at a very early stage, i am prevented from continuing my work due to a linker error when using my makefile, provided below. The error i am receiving is:
g++ controller.o processor.o test.o -o final
controller.o: In function `Controller::run()':
controller.cpp:(.text+0x1e0): undefined reference to
Processor::codeParams(char)'
controller.o: In function `Controller::fetch()':
controller.cpp:(.text+0x290): undefined reference to `Controller::pc'
controller.cpp:(.text+0x299): undefined reference to `Controller::pc'
collect2: error: ld returned 1 exit status
makefile:16: recipe for target 'final' failed
make: *** [final] Error 1
I am unsure as to why i get this error as i thought i had defined these things in the source file corresponding to the header. All files will be given below so that the program can be compiled.
test.cpp:
#include <iostream>
#include <vector>
#include "includes/controller.h"
using namespace std;
int main()
{
vector<char> prog = {0x0};
Controller contr(prog);
cout << "Error Code: " << contr.run() << endl;
return 0;
}
controller.cpp:
/*
Author(s): James Dolan
File: controller.cpp
Build: 0.0.0
Header: includes/controller.h
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#include "includes/controller.h"
Controller::Controller(vector<char> prog)
{
printf("Program:"); //Display program
for(auto i : program)
{
printf("%02X", i);
}
printf("\n");
Controller::program = program;
}
Controller::~Controller ()
{
}
int Controller::run()
{
bool runFlag = true;
int errorCode = 0;
char curCode;
vector<char> curInstr;
int paramRef;
while(runFlag)
{
curCode = fetch();
printf("curCode:%02X\n", curCode);
curInstr.push_back(curCode);
paramRef = proc.codeParams(curCode);
if (paramRef == 0xffff){runFlag = false; continue;} //Check if shutdown signal was returned, if so shutdown
printf("opcode good\n");
for(int i; i<paramRef; i++){curInstr.push_back(fetch());}
}
return errorCode;
}
char Controller::fetch()
{
return program[pc++]; //Return next instruction then increment the program counter
}
controller.h:
/*
Author(s): James Dolan
File: controller.h
Source: ../controller.cpp
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <iostream>
#include <vector>
#include <cstdlib>
#include "processor.h"
using namespace std;
class Controller{
public:
Controller(vector<char> prog);
~Controller();
int run();
protected:
private:
vector<char> program;
static int pc;
char fetch();
Processor proc();
};
#endif
processor.cpp:
#include "includes/processor.h"
Processor::Processor()
{
}
Processor::~Processor()
{
}
int codeParams(char code)
{
switch(code)
{
case 0x0: //Halt
return 0;
default:
printf("[ERROR!] Invalid opcode [%02X]", code);
return 0xffff; //Return shutdown signal
}
}
processor.h:
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <iostream>
#include <cstdlib>
class Processor{
public:
Processor();
~Processor();
int codeParams(char code);
protected:
private:
};
#endif
All if any help is appreciated massively as it will help me to continue with my passion of developing a fully fledged open-source virtual runtime enviroment like the java vm, thank you for your time.
In Controller.cpp you need a int Controller::pc; or int Controller::pc = 0;
In the header file you declared a static int named pc that exists somewhere. It needs to actually exist in a translation unit somewhere (in this case Controller.cpp) so that when the linker tries to find it... it exists.
In Processor.cpp your signature should look like int Processor::codeParams(char code) to let the compiler know that is Processor's codeParams and not a random function named codeParams that happens to also take a character.
For the member function Processor::codeParams you should define it as:
int Processor::codeParams(char code)
// ~~~~~~~~~~~
{
...
}
Otherwise it's just a normal (non–member) function.
For the static member Controller::pc you should define it outside of the class definition, in controller.cpp.
// Controller.h
class Controller {
...
private:
static int pc;
};
// controller.cpp
int Controller::pc;

unique_ptr<> causes compliation errors in C++

I am using this library: https://github.com/Agamnentzar/bluetooth-serial-port
BTSerialPortBinding::Create(address, channelID)
Returns new instance of BTSerialPortBinding object
address: string containint bluetooth address of the device
channelID: ID of the serial port channel
I have a statement:
unique_ptr<BTSerialPortBinding>bt(BTSerialPortBinding::Create(d1.address, 1));
When I separate the statement with the declaration in ArduinoDevice.h and initialisation in ArduinoDevice.cpp in constructor like so:
std::unique_ptr<BTSerialPortBinding> bt;
bt.reset(BTSerialPortBinding::Create("93:83:, 1));
When I added these statements I got the following error:
ArduinoDevice &ArduinoDevice::operator =(const ArduinoDevice &)': attempting to reference a deleted function
Relevant bit in Process.cpp file which is referenced by the error
dev = ArduinoDevice("/dev/tty.IP-DevB");
Process.h
#ifndef __PROCESS_H
#define __PROCESS_H
#define _USE_MATH_DEFINES
#include "ResonantLowpassFilter.h"
#include "ArduinoDevice.h"
//==============================================================================
/**
*/
class AudioProcessor : public AudioProcessor
{
public:
//==============================================================================
WahwahAudioProcessor();
~WahwahAudioProcessor();
void prepareToPlay (double sampleRate, int samplesPerBlock);
void releaseResources();
void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
AudioProcessorEditor* createEditor();
int getNumParameters();
int getNumPrograms();
int getCurrentProgram();
void setCurrentProgram (int index);
const String getProgramName (int index);
void changeProgramName (int index, const String& newName);
float centreFrequency_, q_;
void updateFilterArduino();
ArduinoDevice dev; //instance to an Arduino device from which sensor data is read
};
#endif // _PROCESS
ArduinoDevice.h
#ifndef ArduinoDevice_h
#define ArduinoDevice_h
#include <stdio.h>
#include "BTSerialPortBinding.h"
#include <memory>
class ArduinoDevice
{
public:
ArduinoDevice(const char *dev="");
void connect();
void start(void);
void stop(void);
void read(void);
/**
Disconnects from Arduino device
**/
~ArduinoDevice();
private:
const char *device; //port address of the device (e.g. "/dev/tty.FireFly-E552-SPP")
std::unique_ptr<BTSerialPortBinding> bt; //bt serial port
void close(void);
};
#endif
Edit:
I am using Windows 10, Visual Studio 2015 and Microsoft's C++ Compiler. I am also using an extra JUCE library(https://www.juce.com/).
dev = ArduinoDevice("/dev/tty.IP-DevB"));
dev is declared in the Process.h file above its an instance of ArduinoDevice
My constructor looks like this:
ArduinoDevice::ArduinoDevice(const char *dev)
{
device = dev;
bt.reset(BTSerialPortBinding::Create("98:D3:31:FD:11:1A", 1));
}
I've now tried this in ArduinoDevice.cpp and declaration .h but I still get the same error as above:
ArduinoDevice&&(const char *dev);
{
data = dev.data;
dev.data = nullptr;
}
unique_ptr is not copyable. So when you declare it as a member of your class, your class becomes non-copyable too. The error exactly points that out. (Copy assignment operator is deleted because of that).
Note that usually the move assignment operator is automatically generated by the compiler for you. But in your case since you've explicitly defined a destructor for your class, compiler cant safely define a move assignment operator (or constructor) for you.

Syntax Errors Testing Static Library in C++

I have a very simple setup to try to test a staticLibrary:
I get error Syntax error: Identifier MyDataT, which points me to the function declaration in MyLib.h? Any reason why struct isn't recognized in the second solution?
Here is my pseudo code:
//MSGDefs.h ==> header file only contains struct defs like this:
typedef struct __msg {
unsigned long dest;
unsigned long src;
}MsgT
typedef struct __mydata : public MsgT
{
TimeT time;
DateT date;
}MyDataT;
//======== Library generates staic lib MyLib.lib, this generates library fine=======
//MyLib.h
#include MSGdefs.h
class X{
void process(MyDataT *data);
}
//MyLib.cpp
void X::process(MyDataT *data) { // do processing here ...}
//========================================
//MyTestLibProj.cpp -- Another Solution links to MyLib.lib
#include MyLib.h ==> This causes error of identifier MyDataT ???
int main(){
// X x = new X();
}

LNK2019 error when trying to use a class from a DLL project [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I am working on a directory watcher class for my project.Its .dll type project in c++.I am using Visual Studio 2013 as my IDE.
I followed these basic steps:
1.Created a new project of type dll and c++ language
2.Added the class and dllExport type declaration
3.Build the project
4.Create a new project of type console app
5.Add refernce to the dll project( the two projects are in different directories )
6.Point to the path of header file in Additional include files
But after writing some code that uses.When compiling i get following error
Error 1 error LNK2019: unresolved external symbol "public: __thiscall DirectoryWatcher::DirectoryWatcher(void)" (??0DirectoryWatcher##QAE#XZ) referenced in function "void __cdecl `dynamic initializer for 'watcher''(void)" (??__Ewatcher##YAXXZ) C:\Users\Karthik\documents\visual studio 2013\Projects\ConsoleApplication2\ConsoleApplication2\Source.obj ConsoleApplication2*
But the Dll project build successfully
At the beginning I got error pointing to the destructor but after writing the implementation (empty just braces { }) in header itself.That error was replaced by this one pointing to the constructor
Hers the header file
#define _SCL_SECURE_NO_WARNINGS
#ifdef DIRECTORYWATCHER_EXPORTS
#define APITYPE __declspec(dllexport)
#else
#define APITYPE __declspec(dllimport)
#endif
#if defined(_WIN32)
#define PLATFORM_WINDOWS
#elif __APPLE__
#define PLATFORM_MAC
#elif __linux
#define PLATFORM_LINUX
#endif
//-------------------------------------------
// Code Begins Here
//---------------------------------
#ifndef DIRECTORY_WATCHER_H
#define DIRECTORY_WATCHER_H
#define USE_DIRENT
//------------------------
// Includes
//--------------
#include<vector>
#include<iostream>
#include<fstream>
#include<string>
#include<sys\stat.h>
#include <tchar.h>
#include<map>
#ifdef PLATFORM_WINDOWS
#include<Windows.h>
#endif
#ifdef USE_BOOST
#include<boost/filesystem.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/lexical_cast.hpp>
#endif
#ifdef USE_DIRENT
#include <dirent.h>
#endif
using namespace std;
//Meta File
template<typename T>
struct Meta
{
string Name,Path;
size_t GUID;
float Size;
int Type;
// Can be anything like list of name or list of animation files or list of folder with a folder
vector<T> MetaInfo;
};
//---------------------------------------------
// TYPE DEFS
//-------------------------------------
APITYPE typedef hash<string> HashFunction;
APITYPE typedef Meta<string> FOLDER_META;
struct ChildrenTree
{
vector<Meta<string>> Children;
};
struct DirectoryTree
{
string ParentPath;
//map<Children Name,Related Info>
map<string, FOLDER_META> Child;
};
struct Changed_Data
{
FOLDER_META Old;
FOLDER_META New;
};
//------------------------------------
//operators
//------------------------------------
#ifdef USE_DIRENT
class DirectoryWatcher
{
//-----------------Type Defs------------------------
//typedef Meta<string> FOLDER_META;
public:
//Varaibles
FOLDER_META defaultMeta;
Meta<DirectoryTree> TreeMeta;
// Default Constructor
DirectoryWatcher(void);
~DirectoryWatcher(void){} // Eror at first pointed to the destructor which was solved by defining it here its self
// Obtains a list of files and folders in a directory
APITYPE void GetList(const string&, vector<FOLDER_META>* ReturnValue ,FOLDER_META* ThisDireMeta);
// Searches and Returns the pathto the file
APITYPE bool FindFile(const string& Path
,const string& FileName // File Name
, string* Ret //Path Returned
);
//Update and check to see if a file as moved or added or changed
// Monitor(vector<FOLDER_META>* ChangedFiles,bool* FilesChanged -> return types);
APITYPE void Monitor(vector<Changed_Data>* ChangedFiles,bool* FilesChanged);
// Creates a GUID for a file
APITYPE size_t CreateGUID(const string& fileName);
//Export metadata
APITYPE void ExportMeta(const string& Path,FOLDER_META meta);
// Get the meta data
APITYPE void GetFolderMeta(const string& Path,Meta<string> * ReturnValue );
//InitalizeMethod
// False if path invalid
// true if path correct
APITYPE bool Init(const string& Path //Path to the Project folder (The folder to watch)
);
APITYPE bool Init(const string& Path //Path to the Project folder (The folder to watch)
,vector<FOLDER_META> * Returnmetas);
APITYPE void MakeDir(const string& path);
private:
string Project_Path;
DIR* dir = nullptr;
DIR* MainDir = nullptr;
struct dirent* ent = nullptr;
DIR* tempDir = nullptr;
DirectoryTree Tree;
HashFunction hashFunc;
//Dpeth Search
DirectoryTree UnVisited;
//-------------------------------------
// Windows Specifif cCode
//---------------------------------
HANDLE ChangeNotifications[2];
TCHAR lpDrive[4];
TCHAR lpFile[_MAX_FNAME];
TCHAR lpExt[_MAX_EXT];
DWORD Notifications;
// Private methods
APITYPE long GetFolderSize( const string& Path);
APITYPE bool CheckPathValid(const string& Path);
APITYPE void RefreshFiles(vector<Changed_Data>* ChangedFiles,const string& path,bool OnlyThisFolder);
APITYPE void RefreshTree(vector<Changed_Data>* ChangedFiles, const string& path);
APITYPE void CreateTree(const string& Path );
APITYPE void SaveTree();
APITYPE void LoadTree();
APITYPE bool AreChildEqual(const FOLDER_META& metaA,const FOLDER_META& metaB );
};
#endif
#endif // !DIRECTORY_WATCHER_H
*I Omitted the implementation part as it was very large but here is only the constructor *
DirectoryWatcher.cpp
DirectoryWatcher::DirectoryWatcher(void)
{
Project_Path = "";
dir = nullptr;
MainDir = nullptr;
ent = nullptr;
tempDir = nullptr;
}
The TestAplication
Source.cpp
#include<DirectoryWatcher.h>
using namespace std;
DirectoryWatcher watcher;
// omitted part of code
int main(int argv, char* argc)
{
string Path;
cout << "enterPath";
cin >> Path;
bool ISCahnged;
vector<FOLDER_META> metas,Returnvalues;
vector<Changed_Data> changedDatas;
watcher.Init(Path, &Returnvalues);
while (true)
{
ISCahnged = false;
watcher.Monitor(&changedDatas, &ISCahnged);
if (ISCahnged)
{
for each (Changed_Data var in changedDatas)
{
OutChangedData(var);
}
}
}
return 0;
}
Omitted few lines for smaller code
Can anyone be kind enough to help sort the problem
Thank you
You need to export the class from the dll. There is a very good answer over here: Exporting a C++ class from a DLL

Upgrading some code to build on VS2013 from VS2008 "error C3865: '__thiscall' : can only be used on native member"

I have some code which "works" in VS2008 in that it will build and run and do what I expect. However I have a build error in VS2013, I've managed to reproduce it with just this code:
#include "stdafx.h"
#include <Windows.h>
#include <vector>
template < class T >
class SignatureScanner
{
public:
SignatureScanner(const BYTE* aPattern, const char* aMask, int aExpectedMatches = 1, int aOffSetToFuncStart = 0)
{
}
const std::vector<T> Funcs() const
{
return iFuncs;
}
private:
std::vector<T> iFuncs;
};
// Workaround/hack to define a thiscall function
static void __fastcall fake_this_call_func(void *thisPtr, void* not_used_hack, int aParam)
{
printf("this [%x] param [%d]\n", thisPtr, aParam);
}
// type_traits(396): error C3865: '__thiscall' : can only be used on native member functions
int _tmain(int argc, _TCHAR* argv[])
{
typedef void(__thiscall* myFuncPtr)(int thisPtr, int aParam);
// I use this in some hook code to find a function and redirect it to fake_this_call_func
// which works when it builds
SignatureScanner< myFuncPtr > p(0, 0);
return 0;
}
I want to know why did 2008 not have an error when 2013 does, and how should I go about resolving this error? It only needs to build for Windows XP 32-bit - so platform specific hacks are OK.