First defined here c ошибка

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's user avatar

Vadim Kotov

8,0648 gold badges48 silver badges62 bronze badges

asked Mar 15, 2013 at 20:34

Yasmin Reda's user avatar

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 Mansfield's user avatar

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

HexBlit's user avatar

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

Member Avatar


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.

Member Avatar


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_*/

Member Avatar

15 Years Ago

Move the definition of QStringList FuncCntrlParams::type_pairPotList into the respective .cpp file.

Member Avatar


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’

Member Avatar

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.

Member Avatar


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’

Member Avatar


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++
1
2
3
4
class HOOK32SHARED_EXPORT HookNET32 {
public:
    HookNET32();
};

и реализация:

C++
1
HookNET32::HookNET32(){}

на нее эта ошибка указывает

В принципе они мне не нужны. Мне там нечего инициализировать. Я просто экспортирую extern функции. В этом весь смысл.

Повторных #include у себя не вижу. Здесь находил, что это может быть из-за using namespace в заголовочном файле. Перебрал все в *.cpp-шные. Впрочем судите сами:

alloc.h:

C++
1
2
3
4
#pragma once
 
#include <vector>
#include <windows.h>

main.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma once
 
#ifndef HOOKNET32_H
#define HOOKNET32_H
//#define WIN32
 
#include "hook32_global.h"
#include <iostream>
#include <map>
#include <algorithm>
 
#include "alloc.h"
 
typedef unsigned char BYTE;
typedef unsigned long DWORD;

alloc.cpp

C++
1
2
3
#include "alloc.h"
 
using namespace std;

main.cpp

C++
1
2
3
4
5
6
7
8
#include "main.h"
 
using namespace std;
 
HookNET32::HookNET32(){}
 
typedef map <BYTE,ifunct*> DictOf_Funcs;
typedef vector <vector <void*> > VecV_vp;

PS: так же в каждом заголовочном на вс случай везде поставил #pragme once

В ссылке на стек есть решение, обозначить функции как inline. Я попробовал, действительно, на эту функцию не ругается. Но ругается на следующую. Я думаю, это не есть нормально

Добавлено через 43 минуты
Блин,я думал, что нашел, что ошибку…

У меня в «alloc.h» была структура и класс:

C++
1
2
3
4
5
6
7
8
9
10
11
12
struct jmp_near
{
 
  BYTE push_sign;
  
};
 
class Alloc
{
public:
    int CalcVolume_ByFuncs(std::vector < std::vector<void*> > *funcs_BySign);
};

В alloc.cpp реализация:

C++
1
2
3
4
5
6
7
8
9
10
int Alloc::CalcVolume_ByFuncs(vector<vector<void *> > *funcs_BySign)
{
    int sum = 0;
    for (int i=0;i<funcs_BySign->size();i++){
        for (int j=0;j<funcs_BySign->at(i).size();j++){
            sum++;
        }
    }
    return sizeof(jmp_near)*sum;
}

Как только заменил sizeof(jmp_near) на sizeof(1) все сразу заработало

Но для меня эта ошибка не понятна, т.к. в основном коде я постоянно использую конструкцию sizeof(jmp_near), например, скопировав тело jmp_near в основной код

C++
1
2
3
4
class functD
{
    BYTE old_code[sizeof(jmp_near)];           //старый код
};

И все прекрасно компилировалось и компилируется.

Добавлено через 3 минуты
Короче, только я добавил этот коммент и все перестало компилироваться

Я просто написал одну строку cout << … в основном коде и удалил ее. Откомпилировалось только тогда когда я удалил весь код из alloc.cpp.

Когда же я добавил в alloc.cpp только:

C++
1
2
3
#include "alloc.h"
 
using namespace std;

то он отказался компилироваться и выдал ту же ошибку. Что за фигня?

Добавлено через 12 минут
Теперь он компилируется при:

alloc.h

C++
1
2
3
4
#pragma once
 
#include <vector>
#include <windows.h>

и

alloc.cpp

C++
1
2
3
#include "alloc.h"
 
using namespace std;

Но отказывается, если я добавлю в alloc.h

C++
1
std::vector <std::vector<void*> > Funcs_BySign;

Ничего не пойму. Компилятор мне таким образом запрещает объявить глобальную переменную. Это нормально?

Добавлено через 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 #included 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.

  • Firewyrmnativemessagehost exe ошибка приложения
  • Firestorm ошибка проверки пожалуйста попробуйте еще раз
  • Firefox ошибка синтаксического анализа xml неопределенная сущность firefox
  • Firefox ошибка приложения 0xc0000005
  • Firefox ошибка при запуске приложения 0xc00000022