Qt 5.0 including personal header issues - c++

look i'm kind of new to programming in c++ with Qt so i've downloaded the 5.0 version on my win 7 64 bit. i have made a class named Mafenetre and i implemented its code and it seems perfect but when i i try to run the main program it says
C:\Users\Zbart3i\Downloads\Programs\test\main.cpp:3: error: C1083: Cannot open include file: 'Mafenetre.h': No such file or directory
this is my pro code:
SOURCES += \
main.cpp \
mafenetre.cpp
QT+=widgets
HEADERS += \
mafenetre.h
this is code of Mafenetre.h:
#ifndef MAFENETRE_H
#define MAFENETRE_H
include < QtWidgets>
class Mafenetre:public QWidget
{
public:
Mafenetre();
private:
QPushButton *m_bouton;
};
#endif // MAFENETRE_H
this is Mafenetre's.cpp:
#include "mafenetre.h"
Mafenetre::Mafenetre():QWidget()
{
setFixedSize(300,150);
m_bouton=new QPushButton("pimp mon bouton",this);
m_bouton->setFont(QFont("monotype corsiva",15));
m_bouton->setCursor(Qt::PointingHandCursor);
}
and the main.cpp
#include< QtWidgets/QApplication>
#include< QtWidgets>
#include< Mafenetre.h>
void main(int argc, char *argv[])
{
QApplication app(argc, argv);
Mafenetre fenetre;
fenetre.show();
app.exec();
}

In C++, you should use the #include "name", not #include (Quote marks instead of triangle brackets), as they have different meanings.
#include looks in certain directories where libraries (including the standard library) is installed.
#include "name" looks first in your project's folders, and then checks the other directories.
Well, to be technically accurate, what folders they look in, and in one order, is compiler-specific.
This:
#include <Mafenetre.h>
Should be this:
#include "Mafenetre.h"
Read this:
MinGW #include search directories
Other Directories Searched by Default
The minimal list of directories, identified as described
above, specifies the only locations which will be searched by default,
for system header files or for headers associated with user installed
libraries; however, there is one exception. Astute readers may have
noticed that the include file search path is itemised in a pair of
sequential lists, with the second being concatenated to the first;
however, the first, identified as the #include "..." search list
appears to be empty. In reality, this apparent emptiness is possibly
misleading; unless the user specifies the "-I-" option when invoking
GCC, this list contains exactly one directory: the directory in which
the source file containing the #include "file" directive resides.
Notice that this one additional directory is not searched for headers specified with the #include <file> form of the #include directive; it applies only for those headers specified using the #include "file" form of the directive.
And make sure your "Mafenetre.h" file is in the same folder as your main.cpp file. Otherwise you need to do #include "folderPath/fileName.h", and also add the path to the SOURCES or HEADERS variables in the .pro file.
Also make sure the spelling is identical, and that the proper case is used - sometimes it matters, sometimes it doesn't.
If you are still having trouble, try to compile a simple project consisting of just a single main.cpp, to make sure everything is installed correctly.

Are you sure you have included the right header. Also i don't see you using the QObject macro in your header file. It should be something like this:
Mafenetre.h:
#ifndef MAFENETRE_H
#define MAFENETRE_H
#include <QWidget>
class Mafenetre : public QWidget
{
Q_OBJECT
public:
explicit Mafenetre(QWidget *parent = 0);
signals:
public slots:
};
#endif // MAFENETRE_H
Mafenetre.cpp:
#include "mafenetre.h"
Mafenetre::Mafenetre(QWidget *parent) :
QWidget(parent)
{
}
Finally you main.cpp should be like this, check the headers:
......
#include "mafenetre.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Mafenetre m;
m.show();
return a.exec();
}

Related

Qt console application "WARNING: QApplication was not created in the main() thread"

I'm creating a very simple C++ QT console application from an example given here on stack overflow.
How to use QFileSystemWatcher to monitor a folder for change
The code is exactly as the code in that application and I'm developing with Qt's UI, Qt Creator with MinGW 32bit. I selected the console application from the projects I could choose as I have no need for a graphical user interface. Once the application has finished loading, the application shows the error message "WARNING: QApplication was not created in the main() thread" then does nothing.
I have tried debugging the application but get no breakpoints hit, I don't think debugging is working in the editor.
I had a quick go and changed the QApplication to a QCoreApplication seen as I am developing a console application but get the exact same error message.
filesystemreceiver.h
#ifndef FILESYSTEMRECEIVER_H
#define FILESYSTEMRECEIVER_H
#include <iostream>
using namespace std;
#include <QtCore/QApplication>
#include <QtCore/QFileSystemWatcher>
#include <QtCore/QDebug>
#include <QtWidgets/QWidget>
#include <QtWidgets/QMessageBox>
class MyClass : public QWidget
{
Q_OBJECT
public:
MyClass(QWidget* parent=0)
:QWidget(parent){}
~MyClass() {}
public slots:
void showModified(const QString& str)
{
Q_UNUSED(str)
cout << "A message has been received!" << endl;
//QMessageBox::information(this,"Directory Modified", "Your Directory is modified");
}
};
#endif // FILESYSTEMRECEIVER_H
main.cpp
#include <iostream>
using namespace std;
#include <QtCore/QApplication>
#include <QtCore/QFileSystemWatcher>
#include <QtCore/QDebug>
#include <QtWidgets/QWidget>
#include <QtWidgets/QMessageBox>
#include "fileSystemReceiver.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QFileSystemWatcher watcher;
watcher.addPath("C:/QtTest");
QStringList directoryList = watcher.directories();
Q_FOREACH(QString directory, directoryList)
qDebug() << "Directory name" << directory <<"\n";
MyClass* mc = new MyClass;
QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc, SLOT(showModified(QString)));
return app.exec();
}
My pro file looks like this:
QT += core
QT += widgets
QT -= gui
TARGET = fsw
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
HEADERS += fileSystemReceiver.h
SOURCES += \
main.cpp
You have had several issues ongoing in your project:
QCoreApplication in a program that is supposed to show a QWidget
Calling the main.cpp source file main.moc. That indicates that you do not quite understand how moc works and what it is about.
cout in a Qt program as opposed to QTextStream or qDebug().
Q_FOREACH in a source code not reused by other application, and hence no collision could normally occur. You should use "foreach" simply.
You are not using const reference for the string while iterating with the foreach even though you seem to be only reading it, not modifying.
You have hard coded path here instead of a const string in a well separated place: watcher.addPath("C:/QtTest");
You are adding widgets to the CONFIG variable, but you remove gui.
You are adding `core to the CONFIG variable when that is in there by default.
You include #include <QtWidgets/QFoo> instead of #include <QFoo> to keep the option of building with Qt 4, and in general with clearly buildsystem include paths.
You are adding CONFIG += console for a non-console based application.
You are adding CONFIG -= app_bundle for a non-console based application.
You are using back-slash for the SOURCES variable, but not for the HEADERS. This is inconsitent.
You create a MyClass instance on the heap as opposed to the stack to make it simpler for you as it is already properly guarded by the event loop to remain valid for the intended scope.
On top of all that, your issue seems to be with qDebug() based on the comment discussion. You should follow the document below how to set up QtCreator for debugging properly.
Setting Up Debugger

C++ Qt: can't find methods of dynamic library

I'm working on an application in Qt that has to be plug-able. I've looked around for a while and suddenly came upon an example for plugins in Qt: http://doc.qt.digia.com/4.6/tools-echoplugin.html
I've changed a little something about the classes. I've added a random number generator:
randomgenerator.h:
#ifndef RANDOMNUMBER_H
#define RANDOMNUMBER_H
class RandomNumber
{
public:
~RandomNumber();
RandomNumber();
int getNumber();
};
#endif // RANDOMNUMBER_H
randomgenerator.cpp:
#include "randomnumber.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
RandomNumber::RandomNumber()
{
srand(time(NULL));
}
int RandomNumber::getNumber(){
return rand() % 20;
}
Then I made a small adjustment in the plugin:
echoplugin.cpp:
#include <QtGui>
#include "randomnumber.h"
#include "echoplugin.h"
QString EchoPlugin::echo(const QString &message)
{
RandomNumber* rn = new RandomNumber();
QString a;
a.setNum(rn->getNumber());
return a;
}
Q_EXPORT_PLUGIN2(echoplugin, EchoPlugin);
It's a really simplified version of the program I'm working on. The other classes and methods of the example on the given link haven't been altered.
When I try to execute this program, I get the same error as I have with my own program:
/home/user/qt/v1/echoplugin/echoplugin: symbol lookup error: /home/user/qt/v1/echoplugin/plugins/libechoplugin.so: undefined symbol: _ZN12RandomNumberC1Ev
I ran this through c++filt, and it said that the problem lies with
RandomNumber::RandomNumber()
But I can't find any error concerning that method.
Thanks in advance!
EDIT: by this time, I've solved the problem myself and will now give the explanation for programmers who encounter the same problem.
It's actually a very simple solution: if you want to use code of headers and sourcefiles that are not in the headerfile of your interface, all you have to do is include the relative path in your .pro-file, and that includes both source-files and headerfiles.
So if I wanted to use the RandomNumber class, I'd have to add this to the .pro-file of the plugin:
HEADERS += ../randomnumber.h
SOURCES += ../randomnumber.cpp

field declared void / struct or variable not declared in this scope

I've been teaching myself some OpenGL using SFML for creating windows/handling inputs, etc. My main.cpp started getting a bit unwieldy so I decided to start splitting my code up. I created a 4X_vertex.h and a 4X_vertex.cpp (4X is the name of the project) and moved the relevant functions and structs out of my main and into these files. However, when I compile, I get the error
variable or field "drawVertexArray" declared void
which from my research seems to be just an unhelpful message relating to the next error, which is
vertex was not declared in this scope
Here's my list of includes from my main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include "4x_vertex.h"
#include "4x_constants.h"
My 4X_vertex.h:
#ifndef _4X_VERT_H
#define _4X_VERT_H
struct vertex{
GLfloat x,y,z;
GLfloat r,g,b;
};
void drawVertexArray(vertex v[]);
vertex* loadVertexData();
#include "4X_vertex.cpp"
#endif
The part of 4X_vertex.cpp that's giving me the trouble:
using namespace std;
void drawVertexArray(vertex v[]){
... openGL stuff...
}
All of this worked before I started moving it around so I'm assuming there's something weird going on with the includes, or something. All help is greatly appreciated!
Just some pointers. Best practice is to divide your project up into multiple source files. Typically, you would use the word "main" in the file name of the main source file (if applicable). So you might have something like...
main.cpp
feature1.cpp
feature2.cpp
tools.cpp
For your other files, you will typically name them after the class they implement. You will most often have both a .h and a .cpp. Put your declarations in the .h and your definitions in the .cpp had have the .cpp include the .h. That might give you...
main.cpp
feature1.cpp feature1.h
feature2.cpp feature2.h
tools.cpp tools.h
The modules that reference one of your classes includes it's .h as well. So, main.cpp might look like...
#include <iostream>
#include "feature1.h"
#include "feature2.h"
using namespace std;
void main(int argc, char **argv)
{ ...
cout << "Done!\n";
}
And feature1.cpp might be...
#include "feature1.h"
#include "tools.h"
feature1_class::feature1_class() { ... }
void feature1_class::AUsefulFeature(int val) { ... }
//etc.
...where feature1.h declares the class, defined constants, etc. f.g.,
#ifndef FEATURE1
#define FEATURE1
#include "tools.h"
class feature1_class
{
public:
feature1_class();
void AUsefulFeature(int val);
int APublicMember;
};
#endif
You may have noticed that tools.h is actually include twice in feature1.cpp. It is included from within the feature1.h and explicitly from the .cpp file. If you use the following pattern in your .h files ...
#ifndef TOOLS_H
#define TOOLS_H
//... do your thing
#endif
... then multiple includes shouldn't cause you any problems. And as you refactor code, it is one less thing to have to worry about cleaning up.
If you have been using a single file for all your source up till now, you may have been compiling like so...
cl main.cpp
Which gives you your .exe and .obj and maybe other files. But with multiple source files involved, it isnt much different. You can say...
cl main.cpp feature1.cpp feature2.cpp tools.cpp
There is much more to learn, but this is a start and helps you on the way to better organization of your coding thoughts.
You need to #include "4X_vertex.h" at the top of your 4X_vertex.cpp file. This will allow the .cpp file to see the declaration for the struct vertex.
In general, each file (both .h and .cpp files) needs to #include any header files which contain declarations for items used in that file. This includes the standard headers and OpenGL headers, as well as your custom ones.

Circular dependencies with headers. Using #ifndef and #define

I have the very simple following code:
main.cpp
#include "ui_library_browser.h"
#include <QtGui/QApplication>
#include "StartWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
StartWindow w;
w.show();
return a.exec();
}
StartWindow.h
#ifndef STARTWINDOW_H_
#define STARTWINDOW_H_
#include <qwidget>
#include "MainWindow.h"
class StartWindow : public QWidget
{
Q_OBJECT
public:
StartWindow();
~StartWindow();
MainWindow main_window; //<-- Problem
};
#endif
MainWindow.h
#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_
#include <qdialog.h>
#include "StartWindow.h"
class MainWindow : public QDialog
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
};
#endif
This produces errors because of the inclusion of #include "StartWindow.h" in the MainWindow.h header. However, I thought the use of #ifndef and #define are to stop problems like this? Can someone clear this up for me?
So called "header guards" are used to prevent a bit different kind of error: including same header multiple time through different indirect inclusions in one compile unit. For example,
you include "a.h" from main.cpp and then include "b.h" from main.cpp, that includes "a.h" itself somewhere inside.
In your case two headers try to include each other circurally, that is not possible - C/C++ preprocessor works as simple text "copy-paste" and this case would invent infinite recursion of text insertion.
And I really don't see why would you need "StartWindow.h" inclusion in "MainWindow.h" header.
Do you use StartWindow in MainWindow? If not, simply remove the StartWindow.h include. Otherwise make the main_window a pointer instead of a variable.
In the file StartWindow.h remove #include "MainWindow.h" and add the forward declaration (before class StartWindow ...):
class MainWindow;
In the same file change the member MainWindow main_window to
const MainWindow* main_window;
or
const MainWindow& main_window;
In the latter case you would need to pass const MainWindow& in the constructor of StartWindow.

Undefined reference to 'Class::Class'

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;