1

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

2 Answers 2

6
  1. Your main functions need to be changed to:

    int main() { ... }
    
  2. 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.

  3. 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.

  4. Use getch.cpp and func.cpp to build one executable.

  5. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

Your #include is fine, the problem is that you don't implement fun anywhere.

1 Comment

The error you get is when you compile getch.cpp, not getch2.cpp (which has fun).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.