Reputation: 143
i have 3 C++ source files and i need to call a function from one file into another
getch.cpp
#include<stdio.h>
#include "getch2.h"
main()
{
char ch='x';
fun(ch);
}
getch2.cpp
#include<stdio.h>
void fun(char);
main()
{
}
void fun(char x)
{
printf("the ascii value of the char is %d",x);
}
func.h
void fun(char);
when i compile getch2.cpp i get the error
C:\Users\amolsi\AppData\Local\Temp\cc1k7Vdp.o getch.cpp:(.text+0x18): undefined reference to `fun(char)'
C:\Users\amolsi\Documents\C files\collect2.exe [Error] ld returned 1 exit status
Upvotes: 1
Views: 7573
Reputation: 206717
Your main
functions need to be changed to:
int main() { ... }
Both getch.cpp
and getch2.cpp
contain main
functions. You cannot use them together to form an executable. They'll have to be used to create separate executables.
In order for you to use fun
from getch.cpp
and getch2.cpp
to build executables, you need to move the definition of void fun(char){...}
from getch2.cpp
to another .cpp
file. Let's call it func.cpp
.
Use getch.cpp
and func.cpp
to build one executable.
Use getch2.cpp
and func.cpp
to build the other executable.
Update, in response to OP's comment
File func.h
:
void fun(char);
File func.cpp
:
void fun(char x)
{
printf("the ascii value of the char is %d",x);
}
File getch.cpp
:
#include <stdio.h>
#include "func.h"
int main()
{
char ch='x';
fun(ch);
return 0;
}
File getch2.cpp
:
#include<stdio.h>
#include "func.h"
int main()
{
char ch='y';
fun(ch);
return 0;
}
Use getch.cpp
and func.cpp
to build executable getch.exe
.
Use getch2.cpp
and func.cpp
to build executable getch2.exe
.
Upvotes: 6
Reputation: 138251
Your #include
is fine, the problem is that you don't implement fun
anywhere.
Upvotes: 0