undefined reference

Feb 5, 2009 at 3:41pm
I am getting undefined reference in this code

1
2
3
4
5
6
7
8
9
10
11
12
//>>>>Main.cpp
#include <iostream>
#include "Stack.h"
int main()
{
std::cout << "Stack Program with array :-" << std::endl;
std::cout << Stack::pop() << std::endl;
Stack::push(10);
Stack::push(100);
std::cout << Stack::pop() << std::endl;
return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
//>>>>Stack.h
#ifndef _STACK_H
#define _STACK_H

namespace Stack
{
extern int arr[10];
extern int top;
extern void push(int);
extern int pop();
}
#endif //_STACK_H 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//>>>>Stack.cpp
#include <iostream>
#include "Stack.h"
using namespace std;

int Stack::arr[10];
int Stack::top = 0;
void Stack::push(int num)
{
if(top >= 10)
cout << "Stack overflow" << endl;
else
arr[top++] = num;
}

int Stack::pop()
{
int result = NULL;
if(top <= 0)
cout << "Stack UnderFlow" << endl;
else
result = arr[--top];
return result;
}

The error are :
/tmp/cc66LZ7A.o: In function `main':
Main.cpp:(.text+0x73): undefined reference to `Stack::pop()'
Main.cpp:(.text+0x96): undefined reference to `Stack::push(int)'
Main.cpp:(.text+0xa0): undefined reference to `Stack::push(int)'
Main.cpp:(.text+0xa5): undefined reference to `Stack::pop()'
collect2: ld returned 1 exit status

It is to be noted that the files are getting compiled but are the error kicks in when the linking starts.

Can anybody shade some light in here.

Thanks in advacne
Feb 5, 2009 at 4:15pm
Try not declaring the methods as extern in the class definition. Not sure if that matters, but I've never done it that way.
Feb 6, 2009 at 1:43am
Sounds like you are not linking against both main.o and Stack.o
Feb 6, 2009 at 8:46pm
Yeah it is running now in IDE

i was doing "g++ Main.cpp -o Stack"

But when I seperately compile and then do the linking it is running ?

ie
g++ -c Main.cpp Stack.cpp

g++ Main.o Stack.o -o Stack

It is compiling and running fine.

What is the problem with first command.

PLZ EXPLAIN.
Feb 6, 2009 at 10:44pm
In the first command the compiler doesn't know about the file Stack.cpp . I bet this command would do just fine:

g++ Main.cpp Stack.cpp -o Stack

Both cpp-files need to be preprocessed and compiled to an object-file to be linked properly, so the compiler needs to know about both...
Feb 7, 2009 at 8:24am
Right


Thanks.
Topic archived. No new replies allowed.