Win32 program compiler errors in class definition file - c++

I am trying to Compile in Visual C++ and just added this config file loader/parser to my project. For some ever function defined in class CProfileData is receiving at least one of two errors:
missing type specifier - int assumed.
syntax error : missing ',' before '&'
When obviously this should just be a referenced string
#ifdef UVSS_EXPORTS
#define UVSS_API __declspec(dllexport)
#else
#define UVSS_API __declspec(dllimport)
#endif
class CProfileData
{
public:
UVSS_API CProfileData(){};
UVSS_API CProfileData(const string& profileFile);
UVSS_API ~CProfileData(void);
UVSS_API bool GetVariable( const string& sectionName, const string& variableName, string& valueRet );
UVSS_API bool GetSection( const string& sectionName, SECTION_MAP **pMapRet );
UVSS_API bool GetVariableW( const string& sectionName, const string& variableName, wstring& valueRet );
UVSS_API bool GetVariableInt( const string& sectionName, const string& variableName, int *pIntRet );
private:
void ToLower( string& str );
void TrimWhitespace( string& str);
bool IsComment( const string& str );
bool IsSection( const string& str, string& secName );
bool IsVariable( const string& str, string& name, string& value );
PROFILE_MAP m_mapProfile;
};

Include <string>:
#include <string>
And write std::string wherever you've written string.
Its not a good idea to do either of the following in a header file:
using namespace std; //avoid doing this
using std::string; //avoid doing this as well

Ensure that these two lines appear before including this header:
#include <string>
using std::string;

Related

C++ compile error: redefinition of 'class::class'

I have added the errors within comment lines of the code for the highlighted lines by the compiler.
header file:
#ifndef ADDRESS_H_EXISTS
#define ADDRESS_H_EXISTS
#include <iostream>
#include <string>
using namespace std;
class Address{
private:
string address1;
string address2;
string city;
string state;
string zipCode;
public:
Address(){} //note: 'Address::Address()' previously defined here|
Address(
const string &address1,
const string &address2,
const string &city,
const string &state,
const string &zipCode
){}
NOTE: #endif exists at the end of header file
source file:
#include <iostream>
#include <string>
#include "address.h"
using namespace std;
Address::Address(){} // error: redefinition of 'Address::Address()'
Address::Address( // error: redefinition of 'Address::Address(const string&,
// const string&, const string&, const string&, const string&)'|
const string &address1,
const string &address2,
const string &city,
const string &state,
const string &zipCode
):
address1(address1),
address2(address2),
city(city),
state(state),
zipCode(zipCode)
{
Address::address1 = address1_c;
Address::address2 = address2_c;
Address::city = city_c;
Address::state = state_c;
Address::zipCode = zip_c;
}
All of the most popular questions about this error concluded that header guards were needed, although, there are guards already included in this code.
I thought I was misunderstanding how to properly separate the initialization list between header and source files but when I commented that out it was still producing the same error.
What you're typically supposed to do is define the function prototypes in the header file, and the function definition in the source file. However, in your header file, you seem to have specified a definition of the function already using the empty {} brackets. Hence the compiler is complaining that you've redefined the function definition in the source file. If you remove those two {} empty blocks in the header file and replace them with a semicolon ;, it should solve this error.
Basically, it should look like this in your header:
Address();
Address(
const string &address1,
const string &address2,
const string &city,
const string &state,
const string &zipCode
);
You are getting redefinition errors ( which i think are linker errors, and not compile errors ) because Address::Address() and Address::Address(const string&, const string&, const string&, const string&, const string&) are already defined in the header file, and you define them again in the CPP file
To avoid that, you need to replace function definition by declarations in your header file, by replacing {} by ; in your header file, this way :
public:
Address(); //By replacing '{}' by ';', you change that function definition into a function DECLARATION
Address(
const string &address1,
const string &address2,
const string &city,
const string &state,
const string &zipCode
); // Same for here
At the exception of inline and template functions, function declaration goes in header file, and definitions goes into the CPP file

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

Prototype for PowerSeller::PowerSeller does not match any in class

I'm still fairly new to inheritance and polymorphism, so forgive me. I'm writing a group of derived classes using Scite editor in Linux, and am receiving a compile error stating that my value constructor implementation doesn't match the prototype in the header file.
powerseller.cpp:9:1: error: prototype for \u2018PowerSeller::PowerSeller(std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string)\u2019 does not match any in class \u2018PowerSeller\u2019
powerseller.h:15:3: error: candidates are: PowerSeller::PowerSeller(const PowerSeller&)
powerseller.h:13:3: error: PowerSeller::PowerSeller(std::string, std::string)
powerseller.cpp:7:1: error: PowerSeller::PowerSeller()
Here's my header file. The value constructor is the one throwing the error.
#include "seller.h"
#ifndef POWERSELLER_H
#define POWERSELLER_H
using namespace std;
class PowerSeller : public Seller
{
public:
//constructors & destructors
PowerSeller();
PowerSeller(string fName, string lName, string id, string email, string loc, string date, string numOfStars, string numOfItems, string webAddress, string yearItems);
PowerSeller(const PowerSeller& other);
~PowerSeller();
//member functions
void setWebsite(string webAddress);
void setYearItems(string yearItems);
virtual void print();
virtual void read();
//overloaded operators
bool operator ==(const PowerSeller& rhs);
PowerSeller & operator =(const PowerSeller& rhs);
//overloaded ostream
friend ostream & operator <<(ostream& os, const PowerSeller& rhs);
protected:
string website, items;
};
#endif
Here's the implementation
include "powerseller.h"
#include <iostream>
using namespace std;
PowerSeller::PowerSeller(){}
PowerSeller::PowerSeller(string fName, string lName, string id, string email, string loc, string date, string numOfStars, string numOfItems, string webAddress, string yearItems): Seller(fName, lName, id, email, loc, date, numOfStars, numOfItems){
website = webAddress;
items = yearItems;
}
PowerSeller::PowerSeller(const PowerSeller& other):Seller(other){
website= other.website;
items = other.items;
}
PowerSeller::~PowerSeller(){
website = " ";
items = " ";
}
My ultimate question is: Why is the compiler still showing that PowerSeller's value constructor only accepts two string arguments when I've altered it in the file to match the implementation?

declaration of static function outside of class is not definition

I am getting this error when I compile with GCC:
error: declaration of 'static int utils::StringUtils::SplitString(const std::string&, const std::string&, std::vector<std::basic_string<char> >&, bool)' outside of class is not definition
Code:
Header:
namespace utils
{
/*
* This class provides static String utilities based on STL library.
*/
class StringUtils
{
public:
/**
* Splits the string based on the given delimiter.
* Reference: http://www.codeproject.com/Articles/1114/STL-Split-String
*/
static int SplitString( const std::string& input,
const std::string& delimiter,
std::vector<std::string>& results,
bool includeEmpties = true );
};
};
Source:
namespace utils
{
int StringUtils::SplitString( const std::string& input,
const std::string& delimiter,
std::vector<std::string>& results,
bool includeEmpties );
{
....
}
}
Take the semi-colon off the end of the definition in your source file! Copy-paste error =)
I believe you need to lose that semicolon in your source file. Should be:
namespace utils
{
int StringUtils::SplitString( const std::string& input,
const std::string& delimiter,
std::vector<std::string>& results,
bool includeEmpties ) // <--- No more semi-colon!
{
....
}
}

Undefining functions using preprocessor macros

I've a log system written in C++ with this type of functions to write on it:
void processMessages();
void DEBUG_MSG(const std::string& appender,const char* msg, ...);
void INFO_MSG(const std::string& appender,const char* msg, ...);
void WARNING_MSG(const std::string& appender, const char* msg, ...);
void ERROR_MSG(const std::string& appender, const char* msg, ...);
void FATAL_MSG(const std::string& appender, const char* msg, ...);
I want to disable via macros in C++.
I've read this thread: Disable functions using MACROS but
#ifdef GLOG_SILENCE
#define processMessages (void)sizeof
#define DEBUG_MSG (void)sizeof
#define INFO_MSG (void)sizeof
#define WARNING_MSG (void)sizeof
#define ERROR_MSG (void)sizeof
#define FATAL_MSG (void)sizeof
#else //GLOG_SILENCE
void processMessages();
void DEBUG_MSG(const std::string& appender,const char* msg, ...);
void INFO_MSG(const std::string& appender,const char* msg, ...);
void WARNING_MSG(const std::string& appender, const char* msg, ...);
void ERROR_MSG(const std::string& appender, const char* msg, ...);
void FATAL_MSG(const std::string& appender, const char* msg, ...);
#endif //GLOG_SILENCE
doesn't work properly. I keep getting errors like:
In file included from ../src/test_core.cpp:2:
../src/test_Log.h: In member function ‘virtual void LogTestFixtureTest_defining_SILENCE_macro_avoids_write_and_processing_activity_from_log_Test::TestBody()’:
../src/test_Log.h:63: error: expected unqualified-id before ‘(’ token
../src/test_Log.h:63: error: expected primary-expression before ‘void’
../src/test_Log.h:63: error: expected ‘;’ before ‘sizeof’
../src/test_Log.h:64: error: expected unqualified-id before ‘(’ token
../src/test_Log.h:64: error: expected primary-expression before ‘void’
../src/test_Log.h:64: error: expected ‘;’ before ‘sizeof’
I suspect that the problem is related with the fact that Log is a class, but I don't know how to do it.
Some help?
Indeed, if these are member functions, then the "silent" versions will expand to nonsense:
log.(void)sizeof(stuff);
You could define a member function that does nothing, and macros that swallow their arguments:
void nothing() {}
#define processMessages(...) nothing()
then using the "silent" versions will give valid code that should compile away to nothing:
log.nothing();
The disadvantages of this are (a) you're relying on the compiler to inline the empty function, and not generate a function call; (b) the arguments' syntax is not checked when compiling in silent mode.
If your compiler support variadic macros you can simply define macros with empty replacements:
#ifdef GLOG_SILENCE
#define processMessages(_1, _2, ...)
#define DEBUG_MSG(_1, _2, ...)
#define INFO_MSG(_1, _2, ...)
#define WARNING_MSG(_1, _2, ...)
#define ERROR_MSG(_1, _2, ...)
#define FATAL_MSG(_1, _2, ...)
#else //GLOG_SILENCE
void processMessages();
void DEBUG_MSG(const std::string& appender,const char* msg, ...);
void INFO_MSG(const std::string& appender,const char* msg, ...);
void WARNING_MSG(const std::string& appender, const char* msg, ...);
void ERROR_MSG(const std::string& appender, const char* msg, ...);
void FATAL_MSG(const std::string& appender, const char* msg, ...);
#endif //GLOG_SILENCE
However, this will only work if the functions are NOT members of a class or a namespace, but true global functions.
I would like to suggest you to work in a different way. Just declare the interface ILogger after that implement it in the different loggers, like
class ILogger{
public:
virtual void DEBUG_MSG(const std::string& appender,const char* msg, ...);
virtual void INFO_MSG(const std::string& appender,const char* msg, ...);
virtual void WARNING_MSG(const std::string& appender, const char* msg, ...);
virtual void ERROR_MSG(const std::string& appender, const char* msg, ...);
virtual void FATAL_MSG(const std::string& appender, const char* msg, ...);
virtual ~ILogger(){}
};
For the file logger
class FileLogger : public ILogger{
public:
void DEBUG_MSG(const std::string& appender,const char* msg, ...){....}
void INFO_MSG(const std::string& appender,const char* msg, ...){....}
void WARNING_MSG(const std::string& appender, const char* msg, ...){....}
void ERROR_MSG(const std::string& appender, const char* msg, ...){....}
void FATAL_MSG(const std::string& appender, const char* msg, ...){....}
virtual ~EmptyLogger(){}
};
and the empty logger like:
for the empty logger
class EmptyLogger : public ILogger{
public:
void DEBUG_MSG(const std::string& appender,const char* msg, ...){do nothing here}
void INFO_MSG(const std::string& appender,const char* msg, ...){do nothing here}
void WARNING_MSG(const std::string& appender, const char* msg, ...){do nothing here}
void ERROR_MSG(const std::string& appender, const char* msg, ...){do nothing here}
void FATAL_MSG(const std::string& appender, const char* msg, ...){do nothing here}
virtual ~FileLogger(){}
};
after that in the place where you create the logger could be a factory make a macros in order to generate a different type of logger.
class LoggerFactory{
public:
static ILogger* getLogger(/*loggertype as argument*/){
#ifdef GLOG_SILENCE
/* create a normal logger*/
#else
return new EmptyLogger();
#endif
}
};