-2

Indeed this question is asked and answered many times, but i could not make it correctly to call a function from the main program. I have three separate files as shown below.

//max.h 
int max(int num1, int num2);


//maxmain.cpp
#include <iostream>
#include "max.h"
using namespace std;

// function declaration
int max(int num1, int num2);

int main ()
{
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;

   // calling a function to get max value.
   ret = max(a, b);

   cout << "Max value is : " << ret << endl;

   return 0;
}


//max.cpp
#include "max.h"
// function returning the max between two numbers
int max(int num1, int num2) 
{
   // local variable declaration
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 
}

When i compile maxmain.cpp, i get the error: maxmain.cpp:(.text+0x21): undefined reference to max(int, int) collect2: error: ld returned 1 exit status

  • 1
    Your code is fine, it must be an issue with how you are compiling. What are you using to compile (visual studio, gcc, etc)? – Cory Kramer Mar 21 '16 at 11:38
  • @CoryKramer I am on linux . `g++ maxmain.cpp -o maxmain` – Khawaja Owaise Hussain Mar 21 '16 at 11:40
  • you need to give names of all .cpp files while compiling or link objects after compiling separately. – Akash Sinha Mar 21 '16 at 11:43
  • 2
    Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – crashmstr Mar 21 '16 at 11:44
  • So searching "[c++] undefined reference" got you nothing? I think you did not look closely enough, – crashmstr Mar 21 '16 at 11:46

1 Answers1

2

Your code is fine as written. The issue is how you are compiling. You should list all of the cpp files in this case

g++ maxmain.cpp max.cpp -o maxmain
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218