从cpp

时间:2016-03-21 11:36:02

标签: c++

确实这个问题被多次询问和回答,但我无法正确地从主程序调用函数。我有三个单独的文件,如下所示。

//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; 
}

当我编译maxmain.cpp时,我收到错误: maxmain.cpp:(.text+0x21): undefined reference to max(int, int) collect2: error: ld returned 1 exit status

1 个答案:

答案 0 :(得分:2)

你的代码写得很好。问题是你是如何编译的。在这种情况下,您应列出所有cpp文件

g++ maxmain.cpp max.cpp -o maxmain