I'm making scientific calculator in command line in c++ for my usage and also for practice. I have a problem with compiling it using cmake with mingw on windows. These are my source files:
main.ccp
#include <iostream>
#include <string>
#include "ExpressionCalculations/ExpressionParser.h"
int main()
{
std::string humanReadableExpression;
std::cout<<"Enter expression\n";
std::getline(std::cin, humanReadableExpression);
std::cout<<humanReadableExpression;
ExpressionCalculations::ExpressionParser parser;
auto&& expression = parser.GenerateRpnExpression(humanReadableExpression);
return 0;
}
ExpressionParser.h
#pragma once
#include <memory>
#include <stack>
#include <string>
#include <unordered_map>
namespace ExpressionCalculations
{
class ExpressionParser
{
public:
std::unique_ptr<std::string> GenerateRpnExpression(std::string &humanReadableExpression);
private:
// other code
};
}
ExpressionParser.cpp
#include <memory>
#include <stack>
#include <string>
#include <unordered_map>
#include <iostream>
#include "ExpressionParser.h"
namespace ExpressionCalculations
{
std::unique_ptr<std::string> ExpressionParser::GenerateRpnExpression(
std::string& humanReadableExpression)
{
std::unique_ptr<std::string> rpnExpression;
*rpnExpression="3456";
return rpnExpression;
}
These are cmake files
main CMakeLists.txt
cmake_minimum_required (VERSION 2.8)
project (ScientificCalculator_exe)
add_subdirectory(ExpressionCalculations)
add_executable(ScientificCalculator main.cpp)
target_link_libraries(ScientificCalculator ExpressionCalculations)
module CMakeList.txt
set(calculators ExpressionParser.h ExpressionParser.cpp)
add_library(ExpressionCalculations ${calculators})
When I run it , I can see Enter expression and pass input. Then I get Segmentation fault. However when I remove declaration of ExpressionParser and auto&& expression the string is shown, a string can be inputted and shown in the command. I checked configuration question multiple directories under cmake, https://cmake.org/cmake-tutorial/ and https://www.codeproject.com/Articles/1181455/A-CMake-tutorial-for-Visual-Cplusplus-developers but it seems that I correctly made cmake files. I have no idea why it doesn't work. I use the latest mingw64 on windows with default make compilation parameters.
From the cppreference page on unique_ptr:
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
In your ExpressionParser::GenerateRpnExpression function you are attempting to copy the unique_ptr out of the function when you should be moving it. Try return std::move(rpnExpression)
After debugging program compiled with just g++ I found the problem. It was misunderstanding of unique_ptr' default constructor behaviour. I thought it would initialize std::string but after reading doc and checking it it does not initialize object and generates nullptr. Then I looked into Scott Myers's Modern Effective C++ how to initialize the unique_ptr. Instead of std::unique_ptr<std::string> rpnExpression; I used auto rpnExpression = std::make_unique<std::string>();. It works like charm. I checked compiling through cmake and there were not any problems.
Related
I'm current building an application in which I have a log function that is accessible in most of my classes which was declared as below:
FileHandler.h
#ifndef FILEHANDLER_H
#define FILEHANDLER_H
#pragma once
#include <SDL.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cctype>
//Include to allow logging
#include "log.h"
class fileHandler
{
public:
fileHandler();
virtual ~fileHandler();
void WriteToFile(const std::string& filename, std::string textToWrite);
std::vector<std::string> ReadFromFile(const std::string& filename);
std::string& TrimString(std::string& stringToTrim);
protected:
private:
class log logHandler;
std::vector<std::string> blockOfText;
std::string currentLine;
};
#endif // FILEHANDLER_H
Log.h
#ifndef LOG_H
#define LOG_H
#pragma once
#include <SDL.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <time.h>
class log
{
public:
log();
virtual ~log();
void static WriteToConsole(std::string textToWrite);
void WriteToLogFile(std::string textToWrite);
protected:
private:
};
#endif // LOG_H
This worked fine for a long time and then I wanted to include another function elsewhere in my application that was only compatible with C++11 so I told the compiler to compile to these standards. I was then receiving an error on "log logHandler" saying log is not a declared name.
I was able to resolve the problem by changing the line to
class log logHandler;
I was wondering if anybody could tell me what has changed between C++03 and C++11 that required me to do this?
EDIT: Included all relevant code to make question more complete.
You don't show your real code (missing ; at the end of the class declaration, no #endif), but chances are that your problem is somehow related to std::log, which has received a new overload in C++11, in combination with a using namespace std somewhere in your code.
Note that the new overload is probably irrelevant to the problem at hand; the real reason may very well be a change somewhere in your compiler's standard-library implementation causing an internal #include <cmath>. This means that even in C++03, your code was only working by sheer coincidence, and a conforming C++03 compiler was always allowed to reject it.
Here is an example program which may reproduce your problem:
#include <cmath>
using namespace std;
struct log
{
};
int main()
{
// log l; // does not compile
struct log l; // compiles
}
Nothing has changed about how the code you posted is treated.
What I suspect is, that you somewhere have an
#include <cmath>
And below that, somewhere else
using namespace std;
This causes your compiler to not be able to unambiguously resolve the name log, since there is std::log (a function) and your class log.
By explicitly stating class log, you tell the compiler that you are referring to the class.
I'm working with the boost libraries and opencv, and now I have to implement my own headers and source code (additional to main.cpp) that requires the libraries as well.
The main.cpp looks like (just in principle):
// STL includes
#include <stdlib.h>
...(some other STL stuff)
// Boost includes
#include <boost/array.hpp>
...(a lot of other boost stuff)
//OpenCV
#include <opencv2/opencv.hpp>
// Own header files
#include <myHeader.hpp>
main() do_some_stuff;
This works, if I don't have anything related to boost in myStuff.hpp. But if I add something in it (the function descriptions are in myStuff.cpp), like:
class aClass{
public:
aClass(int);
void doSomething(boost::shared_ptr<int>);
void doSomethingElse(cv::Mat);
};
then it says 'boost' had not been declared, or 'cv' does not name a type.
I was like, ok, I just need to include the headers in this file as well, so I added the same includes, but then when it tries to link it gives a lot of errors like:
/usr/include/boost/operators.hpp:308:35: error: expected identifier before numeric constant
/usr/include/boost/operators.hpp:308:35: error: expected ‘>’ before numeric constant
/usr/include/boost/operators.hpp:310:1: error: expected class-name before ‘{’ token
/usr/include/boost/operators.hpp:311:3: error: expected unqualified-id before numeric constant
...(a lot more of these errors)
I'm using a Makefile to build this project, that looks like:
OPENCV_I = `pkg-config --cflags opencv`
#it finds boost without any additional -I or -L options...
INCLUDEPATHS = $(OPENCV_I)\
-I.\
-L.
LIBS=-lGL -lGLU -lm -lboost_program_options -lboost_system -lboost_thread -pthread -lrt -lopencv_core -lopencv_highgui
SRCCXX := main.cpp myStuff.cpp
OBJSCXX := $(SRCCXX:%.cpp=${BUILDDIR}/%.o)
$(BUILDDIR)/%.o : %.cpp
$(CXX) $(CXXFLAGS) $(INCLUDEPATHS) -c $< -o $# -DdDOUBLE $(LIBS)
all: ${OBJSCXX}
$(CXX) $(LDFLAGS) $(INCLUDEPATHS) -o $(OUTNAME) $? -DdDOUBLE $(LIBS)
Previously I was using CMake, and it worked quite well with these kind of projects, just this one is a part of a bigger project where they use Makefiles for everything. So I guess the main problem is with the makefile, probably when I list my source codes SRCCXX := main.cpp Visualisation.cpp it doesn't like it...
Any suggestions?
Thank you in advance.
EDIT....................................
So my whole myStuff.hpp looks like:
#define _USE_MATH_DEFINES
#include <math.h>
#define RINGS 5
#define SECTIONS 12
// Boost includes
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/assign/ptr_list_of.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/date_time.hpp>
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/program_options.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <opencv2/opencv.hpp>
class Sensor{
public:
Sensor(int);
void Update(boost::shared_ptr<char[RINGS][SECTIONS]>);
int Id();
private:
char data[RINGS][SECTIONS];
int id;
};
and the myStuff.cpp:
#include "myStuff.hpp"
void Sensor::Update(boost::shared_ptr< char[RINGS][SECTIONS] > buffer){
for(int i=0;i<RINGS;i++) for(int j=0;j<SECTIONS;j++) data[i][j]=buffer[i][j];
};
Sensor::Sensor(int a){
id=0;
};
int Sensor::Id(){
return id;
};
and my main.cpp:
// STL includes
#include <stdlib.h>
#include <iostream>
#include <mutex>
#include <string.h>
#include <typeinfo>
#include <queue>
#include <memory>
// Boost includes
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/assign/ptr_list_of.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/date_time.hpp>
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/program_options.hpp>
#include <boost/numeric/ublas/matrix.hpp>
//OpenCV
#include <opencv2/opencv.hpp>
// Own header files
#include "myStuff.hpp"
////////////////////////////////////////// Main
int main (int argc, char **argv)
{
Sensor sensor(0);
return 0;
}
Well first things first... when including your own headers from within your project I would recommend that you use "mine.hpp" instead of <mine.hpp>. This ensures that the compiler won't search the complete include path and accidentally find some other include of the same name (different version for example).
Second, when you have a dependency within a class then you include the header for that dependency within that class. You cannot make assumptions that someone will include all your dependencies in a main class or some other class. Sometimes someone will just want to use your class by itself. You don't want them to then have to figure out your dependencies. Don't worry about replication either as the include guard (or pragma) will prevent that.
As for your particular problems you will need to give use your code. You have certainly managed to correctly include your headers at that point. I would guess that they might stem from a missing { or ; somewhere. Look at your very first error and solve that one.
EDIT
The issue appears to be with how you are using boost. I had a look at what in operators.hpp and in version 1_44 what I see is a struct definition with 4 template parameters, one of which is defaulted to boost::detail::empty_base<T>. Only thing I can say is to make sure that you have your entire boost library on your include path, and link path.
EDIT2
From your newly posted code I see a couple of problems. First is that you have WAY too many includes in your header. You should only ever have class dependency includes in your header, and always prefer to put your header files into your implementation (.cpp) file. This helps to prevent extremely long compilation times. So first modify your header to include only the dependencies you need:
#include <boost/shared_ptr.hpp>
#define RINGS 5
#define SECTIONS 12
class Sensor{
public:
Sensor(int);
void Update(boost::shared_ptr<char[RINGS][SECTIONS]>);
int Id();
private:
char data[RINGS][SECTIONS];
int id;
};
Then in your implementation the only change is to put braces around your for loops (this is for clarity and safety... understand why you put it on one line but it is not worth it). Also put your CTOR first:
#include "myStuff.hpp"
Sensor::Sensor(int a){
id=0;
};
void Sensor::Update(boost::shared_ptr< char[RINGS][SECTIONS] > buffer){
for(int i=0;i<RINGS;i++) {
for(int j=0;j<SECTIONS;j++) {
data[i][j]=buffer[i][j];
}
}
};
int Sensor::Id(){
return id;
};
Main
#include "myStuff.hpp"
int main (int argc, char **argv)
{
Sensor sensor(0);
return 0;
}
The ONLY dependency you need is boost::shared_ptr. To be honest though, I'm pretty sure you don't need that either. Anyway I would recommend that you start with the above and then build up by adding one dependency at a time.
After a couple of hours I figured it out. myStuff.cpp also requires the header inclusion. Silly mistake, but still why can't the compiler says something like non defined or can't find instead of a couple of pages of messed up errors...?
Thanks anyway for your help.
I have this map which compiles fine in MSVC10 :
std::map<std::string, std::ofstream> m_logFiles;
But on ubuntu using g++ 4.5 with C++0x enabled, I get the following error message :
/usr/include/c++/4.5/bits/ios_base.h|785|error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private
By using pointers instead of objects, I resolved the problem.
Searching on the web, I learned that streams are not meant to be copied (the why was well explained). But my question is, is std::ofstream a movable type ? If it is, shouldn't it allow its use as a template parameter in the standard containers ?
If yes, then is g++ behind MSVC10 on this point ? (which would explain why it works on MSVC). I know it would be silly to ask compiler writers to fully implement something that isn't even final, but I'm curious regarding the future.
Using g++ 4.6.1 didn't help.
Edit : reading the comments I dug a little bit further and found that the insert is causing the problem, not the declaration of the map.
Reading Cubbi's link I tried the following :
#include <string>
#include <fstream>
#include <map>
using namespace std;
int main()
{
map<string, ofstream> m_logFiles;
ofstream st;
m_logFiles.insert(make_pair<string, ofstream>(string("a"), move(st)));
return 0;
}
But still no luck. g++ complains about the use of b deleted copy constructor.
std::ofstream is movable. This program compiles for me using clang/libc++:
#include <string>
#include <fstream>
#include <map>
int main()
{
std::map<std::string, std::ofstream> m_logFiles;
}
Reference 27.9.1.11 [ofstream.cons].
I asked a similar question earlier, and later found that GCC doesn't seem to support movable fstreams yet (I just tested GCC 4.6.1) as detailed in this answer.
I am trying to compile the following code:
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/assign/std/vector.hpp>
#include <boost/optional.hpp>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/algorithm/copy.hpp>
int main( int argc, char ** argv )
{
using namespace boost::assign;
using boost::adaptors::indirected;
std::vector<boost::optional<unsigned> > values;
values += 1u,2u,3u;
boost::copy( values | indirected, std::ostream_iterator<unsigned>( std::cout, " " ) );
std::cout << std::endl;
}
However, I got some errors, e.g. that there is no type named element_type in boost::optional<unsigned>. The reference page page, however, says that the single precondition is the existence of the operator*() unary function. Is there a way to make it work?
This is definitely a bug in Boost, but whether that bug is in Boost.Optional or Boost.Iterator is up for debate (I would say the latter, personally).
However, the fix is trivial -- before including any Boost headers, do this:
#include <boost/optional/optional_fwd.hpp>
#include <boost/pointee.hpp>
namespace boost
{
template<typename P>
struct pointee<optional<P> >
{
typedef typename optional<P>::value_type type;
};
}
Then include other Boost headers as necessary.
Please submit a ticket on the Boost Trac, or at the least post a bug report on the Boost Users mailing list.
Look at the private optional.hpp defined in boost iostreams library here. You will see that it defines a typedef T element_type;
However the actual optional.hpp that you are using defined here does not define it. So that is why the compiler is complaining. I don't know why it was overlooked.
Try using the private optional.hpp from iostreams library to solve this issue. I hope this helps.
After fixing the previous problem (see my one other question that I have asked). I had declared more classes.
One of these is called CombatAdmin which does various things: (Header file)
#ifndef COMBATADMIN_H
#define COMBATADMIN_H
#include <string> // Need this line or it complains
#include <Player.h>
#include <Sound.h>
#include <Enemy.h>
#include <Narrator.h>
using namespace std;
class Enemy;
class Player;
class CombatAdmin // Code yet to be commented here, will come soon.
{
public:
CombatAdmin();
void healthSet(double newHealth, string playerName);
void comAdSay(string sayWhat);
void playerFindsChest(Player *player,Weapon *weapon,Armour *armour);
void youStoleOurStuffEncounter(Player *player);
void comAdWarning(string enemyName);
void comAdAtkNote(string attack, double damage,string target,string aggresor);
void entDefeated(string entName);
void comAdStateEntHp(string ent, double hp);
void comAdStateScanResults(string enemyName, double enemyHealth);
string doubleToString(double number);
string intToString(int number);
bool isRandEncounter();
void randomEncounter(Player *player,Sound *sound,Narrator *narrator);
bool combatRound(Player *player, Enemy *enemy, Sound *sound, bool ran);
void playerFindsItem(string playerName,string itemName,double itemWeight,double playerWeight);
void playerFindsGold(string playerName,double coinCnt,double playerCoinCnt);
};
#endif // COMBATADMIN_H
It is then instanced in the main.cpp file like this: (Snippet of the main.cpp file)
#include <iostream> // Required for input and output
#include <Item.h> // Item header file.
#include <Weapon.h> // Header files that I have made for my classes are needed for this program
#include <sstream> // Needed for proper type conversion functions
#include <windows.h> // for PlaySound() and other functions like sleep.
#include <time.h> // Needed to seed the rand() function.
#include <mmsystem.h> // Not sure about this one, possibly defunct in this program.
#include <stdio.h> // Needed for a similar kind of output as iostream for various functions error msgs.
#include <irrKlang.h> // The header file of the sound lib I am using in this program.
#include <Narrator.h> // The narrators's header file.
#include <Pibot.h> // Other header files of classes.
#include <Armour.h>
#include <Player.h>
#include <Weapon.h>
#include <CombatAdmin.h>
using namespace irrklang;
using namespace std;
// Forward referenced functions
void seedRandom(); // Seeds the random number so it will be random as apposed to pseudo random.
string getPlayerName(string temp); // Gets the player's new name.
int main(int argc, char* argv[])
{
// Variables and object pointers declared here.
CombatAdmin *comAd = new CombatAdmin(); // Handles combat.
Narrator *narrator = new Narrator(); // The Narrator that says stuff
Pibot *piebot = new Pibot(); // PIbot, the player's trusty companion
string temp; // Temp string for input and output
However, when I try to compile the project, I get the following error:
C:\Documents and Settings\James Moran.HOME-B288D626D8\My Documents\C++ projects\Test Project\main.cpp|59|undefined reference to `CombatAdmin::CombatAdmin()'|
I am using the Code::Blocks IDE (ver 10.05), with the GNU GCC compiler. The project is of type "Console application". I am using windows XP 32 bit SP3.
I have tried changing to search directories to include where the object files are, but no success there.
As can be seen from the code, the narrator and PIbot are instanced just fine. (then used, not shown)
My question is, therefore, what do I need to do to stop these errors occurring? As when I encountered similar "Undefined reference to x" errors before using libraries. I had just forgotten to link to them in Code::Blocks and as soon as I did, they would work.
As this class is of my own making I am not quite sure about this.
Do say if you need more information regarding the code etc.
You have declared the default constructor (CombatAdmin()) and thus prevented the compiler from automatically generating it. Thus, you either need to 1) remove declaration of the default constructor from the class, or 2) provide an implementation.
I had this kind of error and the cause was that the CombatAdmin.cpp file wasn't selected as a Build target file: Prject->Properties->Build targets
Are you sure you've to include your header as:
#include <CombatAdmin.h>
?
I think you need to include your header file as:
#include "CombatAdmin.h"
And same for other headers written by you, like these:
#include "Armour.h"
#include "Player.h"
#include "Weapon.h"
//and similarly other header files written by you!
See this topic:
What is the difference between #include <filename> and #include "filename"?
My solution was just to add a line in the header before the class defenition:
class CombatAdmin;