The problem here is that you are including commands.c
in commands.h
before the function prototype. Therefore, the C pre-processor inserts the content of commands.c
into commands.h
before the function prototype. commands.c
contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.
The content of commands.h
after the pre-processor phase looks like this:
#ifndef COMMANDS_H_
#define COMMANDS_H_
// function definition
void f123(){
}
// function declaration
void f123();
#endif /* COMMANDS_H_ */
This is an error because you can’t declare a function after its definition in C. If you swapped #include "commands.c"
and the function declaration the error shouldn’t happen because, now, the function prototype comes before the function declaration.
However, including a .c
file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h
in commands.c
and link the compiled version of command to the main file. For example:
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123(); // function declaration
#endif
commands.c
#include "commands.h"
void f123(){} // function definition
I have an error that i can’t include my header file in more than one cpp even though i have guard headers.
when removing the include of DatabaseManager from main the ccode builds just fine
here is the header file :
#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H
#include <QSqlDatabase>
#include <QSqlQuery>
class DatabaseManager
{
private:
QSqlDatabase PatternLibrary;
QSqlQuery query;
public:
DatabaseManager();
};
#endif
here is the .cpp:
#include "DatabaseManager.h"
#include <QSqlError>
#include <QDebug>
DatabaseManager::DatabaseManager()
{
}
and here is the main :
#include "DatabaseManager.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DatabaseManager x;
MainWindow w;
w.show();
return a.exec();
}
giving these errors :
/Code/DB_RangePattern-build-desktop-Qt_4_8_1_in_PATH_System_Debug/../DB_RangePattern/main.cpp:6: error: first defined here
collect2: ld returned 1 exit status
Vadim Kotov
8,0648 gold badges48 silver badges62 bronze badges
asked Mar 15, 2013 at 20:34
7
You’ve only posted one line of a larger error, but I can hazard a guess at what the problem is. You seem to be unsure of whether your class is DataBaseManager
or DatabaseManager
(note the change in capital B
).
Also, if your header file is with the rest of your source files, make sure you’re doing #include "DatabaseManager.h"
(not using <
and >
).
answered Mar 15, 2013 at 20:44
Joseph MansfieldJoseph Mansfield
108k20 gold badges241 silver badges323 bronze badges
1
I am pretty sure QSqlDatabase uses/include QSqlError because it has a defined public function
QSqlError lastError () const
and redefinition will come from your including QSqlError
answered Mar 15, 2013 at 20:47
HexBlitHexBlit
1,1721 gold badge13 silver badges30 bronze badges
3
Recommended Answers
It’s a shot in the dark, but if you include a .h or .cpp file more than once and don’t do something like this:
#ifndef ... #define ... // code #endif
you could get that error. I’m not saying that is the cause here, but it’s something …
Jump to Post
Move the definition of QStringList FuncCntrlParams::type_pairPotList into the respective .cpp file.
Jump to Post
All 7 Replies
VernonDozier
2,218
Posting Expert
Featured Poster
15 Years Ago
It’s a shot in the dark, but if you include a .h or .cpp file more than once and don’t do something like this:
#ifndef ...
#define ...
// code
#endif
you could get that error. I’m not saying that is the cause here, but it’s something to consider.
Kob0724
20
Junior Poster in Training
15 Years Ago
Yea, I already have those in the .h file. I tried something new though. I took the reference to type_pairPotList out of interpotcntrlparams.cpp and I still got the error. This time it was this:
debug/mymetawindow.o: In function `qt_noop()’:
/home/f07/xxx/QT/include/QtCore/qglobal.h:1425: multiple definition of `FuncCntrlParams::type_pairPotList’
make[1]: Leaving directory `/net/home/f07/xxx/workspace/tramontoGUI’
debug/funccntrlparams.o:/home/f07/xxxx/QT/include/QtCore/qglobal.h:1425: first defined here
debug/moc_funccntrlparams.o: In function `qt_noop()’:
/home/f07/xxx/QT/include/QtCore/qglobal.h:1425: multiple definition of `FuncCntrlParams::type_pairPotList’
debug/funccntrlparams.o:/home/f07/xxx/QT/include/QtCore/qglobal.h:1425: first defined here
So it would seem like the problem is squarely located in my funcctnrlparams.h file. Here’s that file with a little more detail:
#ifndef FUNCCNTRLPARAMS_H_
#define FUNCCNTRLPARAMS_H_
#include <QWidget>
#include <QStringList>
class FuncCntrlParams : public QWidget
{
Q_OBJECT
public:
/**
* Constructs a new FuncCntrlParams QWidget.
*/
FuncCntrlParams(QWidget *parent=0);
static QStringList type_pairPotList;
};
QStringList FuncCntrlParams::type_pairPotList = QStringList() << "Pair LJ12-6 CS" << "Pair Coulomb CS" << "Pair Coulomb" << "Pair Yukawa CS";
#endif /*FUNCCNTRLPARAMS_H_*/
15 Years Ago
Move the definition of QStringList FuncCntrlParams::type_pairPotList into the respective .cpp file.
Kob0724
20
Junior Poster in Training
15 Years Ago
I can’t do that. I have to define it in the header file or else I get this error:
net/home/f07/xxx/workspace/tramontoGUI/interpotcntrlparams.cpp:48: undefined reference to `FuncCntrlParams::type_pairPotList’
15 Years Ago
I can’t do that. I have to define it in the header file or else I get this error:
You need to #include the respective header file in interpotcntrlparams.cpp.
Kob0724
20
Junior Poster in Training
15 Years Ago
You need to #include the respective header file in interpotcntrlparams.cpp.
Yea I did do that.
interpotcntrlparams.cpp
//interpotcntrlparams.cpp
#include "interpotcntrlparams.h"
#include "surfcntrlparams.h"
#include "funccntrlparams.h"
.
.
.
And I still get the error:
net/home/f07/xxx/workspace/tramontoGUI/interpotcntrlparams.cpp:48: undefined reference to `FuncCntrlParams::type_pairPotList’
Kob0724
20
Junior Poster in Training
15 Years Ago
I figured it out. The problem was that I was defining type_pairPotList in the constructor of FuncCntrlParams. Like this:
//funcntrlparams.cpp
.
.
FuncCntrlParams::FuncCntrlParams(QWidget *parent)
:QWidget(parent)
{
QStringList type_pairPotList = QStringList() << "Pair LJ12-6 CS" << "Pair Coulomb CS" << "Pair Coulomb" << "Pair Yukawa CS";
.
.
}
.
.
Once I took it out of the constructor like this:
//funcntrlparams.cpp
.
.
QStringList type_pairPotList = QStringList() << "Pair LJ12-6 CS" << "Pair Coulomb CS" << "Pair Coulomb" << "Pair Yukawa CS";
FuncCntrlParams::FuncCntrlParams(QWidget *parent)
:QWidget(parent)
{
.
.
}
.
.
Everything worked.
Thanks for bearing with me mitrmkar. I’m still transitioning from Java and I think because of my Java mindset I figured since I’d already declared the variable outside of the constructor, the only place to define it now would be in the constructor.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Друзья, что это за ошибка?
Ниже присказка: «collect2: ld returned 1 exit status»
читал. Пишут. что из-за повторных #include-ов. Но не пойму, где я напортачил
Среда QT Creator
Проект — dll. При создании автоматически средой был создан конструктор:
C++ | ||
|
и реализация:
C++ | ||
|
на нее эта ошибка указывает
В принципе они мне не нужны. Мне там нечего инициализировать. Я просто экспортирую extern функции. В этом весь смысл.
Повторных #include у себя не вижу. Здесь находил, что это может быть из-за using namespace в заголовочном файле. Перебрал все в *.cpp-шные. Впрочем судите сами:
alloc.h:
C++ | ||
|
main.h
C++ | ||
|
alloc.cpp
C++ | ||
|
main.cpp
C++ | ||
|
PS: так же в каждом заголовочном на вс случай везде поставил #pragme once
В ссылке на стек есть решение, обозначить функции как inline. Я попробовал, действительно, на эту функцию не ругается. Но ругается на следующую. Я думаю, это не есть нормально
Добавлено через 43 минуты
Блин,я думал, что нашел, что ошибку…
У меня в «alloc.h» была структура и класс:
C++ | ||
|
В alloc.cpp реализация:
C++ | ||
|
Как только заменил sizeof(jmp_near) на sizeof(1) все сразу заработало
Но для меня эта ошибка не понятна, т.к. в основном коде я постоянно использую конструкцию sizeof(jmp_near), например, скопировав тело jmp_near в основной код
C++ | ||
|
И все прекрасно компилировалось и компилируется.
Добавлено через 3 минуты
Короче, только я добавил этот коммент и все перестало компилироваться
Я просто написал одну строку cout << … в основном коде и удалил ее. Откомпилировалось только тогда когда я удалил весь код из alloc.cpp.
Когда же я добавил в alloc.cpp только:
C++ | ||
|
то он отказался компилироваться и выдал ту же ошибку. Что за фигня?
Добавлено через 12 минут
Теперь он компилируется при:
alloc.h
C++ | ||
|
и
alloc.cpp
C++ | ||
|
Но отказывается, если я добавлю в alloc.h
C++ | ||
|
Ничего не пойму. Компилятор мне таким образом запрещает объявить глобальную переменную. Это нормально?
Добавлено через 56 секунд
PS: пересборка не помогает. Смириться?
(This smells like a homework assignment.)
First, the error message:
boo.c multiple definition of main
light.o:light.c:first defined here.
It indicates the files you’re attempting to link together have multiple copies of a function named main()
, and that is clearly not correct.
You’re trying to reuse light.o
, but that would really work only if it had a function other than main()
. Let’s call it light()
. You would also need a .h
file #include
d in boo.c
, so that the compiler will know the properties (basically the types of the parameters and the type of return value, if it has any) of the function light()
without yet seeing its source code.
It seems to me that your files fit together somewhat differently from what is expected in the assignment. Your professor may have created a series of assignments that tie together: if you take shortcuts in the previous assignments in the series, the later assignments that reuse code from the previous ones won’t work right.
Your professor is attempting to teach you how to arrange your code so that it’ll be reusable, and what happens if you fail to do so.
The basic form of Makefile rules is:
<name of target>: <names of files the creation process depends on>
<command(s) to create the target file>
The creation of a .c
file depends not only of the file itself, but also of the .h
files it includes. Generally you can assume that any system include files (those you include with #include <filename>
won’t change on you, so you won’t need to add those into your Makefile rules. But any .h
files that are part of your project should be included too.
There can also be «virtual targets» that are not actually files. They allow you to do things like make clean
. You can also use a virtual target as a dependency of another target: since a virtual target does not have a real file associated with it, the commands to «create» the virtual target will be executed each time the virtual target is listed as a dependency for something else and that something else needs to be built.
Also, there can be Makefile rules that don’t have any commands in them, but list one or more Makefile targets as their dependencies. If there is just one dependency, then the target with no commands acts just as an another name to the target listed as a dependency. If it has multiple dependencies, then the command-less target becomes a way to have multiple Makefile targets built with a single command.
It sounds to me like your professor intended the build:
target to become such a target with no commands of its own. It should just depend on two targets:
- a separate target to build the actual executable
- the
templates
target
You may wonder how I knew about the contents of light.o
without seeing its source code? Simple — I downloaded your light.o
and then used this command:
$ readelf -s light.o
Symbol table '.symtab' contains 12 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS light.c
2: 00000000 0 SECTION LOCAL DEFAULT 1
3: 00000000 0 SECTION LOCAL DEFAULT 3
4: 00000000 0 SECTION LOCAL DEFAULT 4
5: 00000000 0 SECTION LOCAL DEFAULT 5
6: 00000000 0 SECTION LOCAL DEFAULT 7
7: 00000000 0 SECTION LOCAL DEFAULT 8
8: 00000000 0 SECTION LOCAL DEFAULT 6
9: 00000000 51 FUNC GLOBAL DEFAULT 1 main
10: 00000000 0 NOTYPE GLOBAL DEFAULT UND puts
11: 00000000 0 NOTYPE GLOBAL DEFAULT UND sound
That tells me light.o
comes from a source file named light.c
, defines a function named main()
and uses functions named puts()
and sound()
, which are not defined here. puts()
comes from the standard library, but sound()
needs to be defined in some other file that is linked together with this one to make a complete executable.