繁体   English   中英

从cpp中的主函数调用函数

[英]Calling a function from main function in cpp

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM