I am trying to implement a Stack in a program using C language. I separate them into 3 file.
First, stack.h file. It include some essential declaration and function such as Pop, Push for a stack. Second, stack.c file. It is a file implement the function inside stack.h file. In my case, I implement my stack using a dynamic array. Third, main.c file. It is where I use Stack to do some calculation.
However, I get LNK2005(...already defined in ...obj) compile error at the end. I know this error would happen when there exist a multiple times of definition. However, I saw many example with same function name in .h/.c file but didn't cause a error.
Here is the error log:
LNK1169 one or more multiply defined symbols found
LNK2005 _CreateStack already defined in main.obj
LNK2005 _IsEmpty already defined in main.obj
LNK2005 _Pop already defined in main.obj
LNK2005 _Push already defined in main.obj
LNK2005 _StackDepth already defined in main.obj
Thanks for you kindly attention. Here is my stack.h file.
typedef struct Stack Stack;
Stack* CreateStack();
void Push(Stack *s, char InputString);
void Pop(Stack *s);
int StackDepth(Stack *s);
int IsEmpty(Stack *s);
Here is my stack.c file.
#include "stack.h"
typedef struct Stack{
.....
.....
}
Stack* CreateStack(){
......
};
void Push(Stack *s, char InputString){
....
....
}
void Pop(Stack *s){
....
};
int StackDepth(Stack *s){
....
};
int IsEmpty(Stack *s){
....
};
Here is my main.c file
#include<stdio.h>
#include"stack.c"
#include"stack.h"
int main(){
....
....
....
return 0;
}
You have included your C file in your main file.
The #include
directive tells the pre-processor to textually paste the entire content of the file specified into the location where the #include
directive is. This means that your function implementations from the stack.c
file are now compiled both as part of your stack.c
file and your main.c
file - implemented twice, as your linker tells you.
The compiler can't deal with ambiguity - it there are 2 matching functions for a call, it returns an error instead of randomly choosing one of them.
You should never #include
C files, only headers (.h) files.