Reputation: 5776
I'm having a linking issue with a basic C++ program. No, I'm not including .cpp
files!
This is what's happening.
main.cpp:
#include "header.h"
#include <iostream>
int main() {
std::cout << "Hello!";
}
header.h:
#ifndef _HEADER_H
#define _HEADER_H
class Something {
public:
printContents();
};
#endif
something.cpp:
#include "header.h"
#include <iostream>
Something::printContents() {
cout << "This class's Contents!!";
}
What's happening is that I get a compiler error going: multiple definitions of some standard C function, such as strtod
:
g++ -o ... main.o
build/....main.o: In function `strtod':../MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/stdlib.h:318: multiple definition of `strtod'
build/..something.o:...something.cpp:(.text+0x0): first defined here collect2: ld returned 1 exit status
If I get rid of #include <iostream>
in one of the two occasions and get rid of the cout
s, it will compile. What's going on? I'm using g++ and NetBeans to compile.
I tried in the command line:
g++ *.h *.cpp -o program
and the same thing happened.
Upvotes: 0
Views: 486
Reputation: 5776
The problem was in a multi-installation of MinGW. I had one already installed, and when I got Qt on my computer, it had installed it's own MinGW. Bummer, I ported the code to my university's servers and it ran OK.
Bummer!!
Thanks everybody for the help, I will definitely follow your guidelines in the future.
Header names - no underscores Correct return type Real code in the forums!
Leo Bruzzaniti
Upvotes: 0
Reputation: 7921
I see a couple of problems. You shuold define the returning value of the function
printContents()
and you must write
std::cout
if you don't write
using namespace std;
Upvotes: 2
Reputation: 22089
I could not reproduce your exact problem. I get this to compile and link nicely with the following few notes:
void
return type to the printContents
-function (So it says void printContents();
in the header and void Something::printContents() {
in the implementation-file)std::cout
rather than just cout
. cout
is not defined in the scope it is usedHEADER_H
rather than _HEADER_H
(like Neil Butterworth says)I use the command line g++ main.cpp something.cpp
to compile.
Upvotes: 3
Reputation: 94645
Modify,
Something::printContents()
{
std::cout << "This class's Contents!!";
}
NOTE: Specify the return datatype.
Upvotes: 4
Reputation:
Please note that _HEADER_H
is an illegal name in C++ user code - names beginning with the underscore and an uppercase letter are reserved for the C++ implementation. This does not normally cause noticeable problems, but when you use what may be a common name in the implementation like HEADER in this context, it well might.
Upvotes: 4
Reputation: 10670
One of your problems is right here:
I tried in the command line: g++ *.h *.cpp -o program
Don't pass your header files... Try something like this:
g++ *.cpp -o program
Upvotes: 3