Tatsächlich wird diese Frage oft gestellt und beantwortet, aber ich konnte es nicht richtig machen, eine Funktion aus dem Hauptprogramm aufzurufen. Ich habe drei separate Dateien wie unten gezeigt.Aufruf einer Funktion aus der Hauptfunktion 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;
}
Wenn ich maxmain.cpp
kompilieren, erhalte ich die Fehlermeldung: maxmain.cpp:(.text+0x21): undefined reference to max(int, int) collect2: error: ld returned 1 exit status
Ihr Code ist in Ordnung, es muss ein Problem sein mit, wie Sie kompilieren. Was benutzt du zum kompilieren (Visual Studio, GCC, etc)? – CoryKramer
@CoryKramer Ich bin auf Linux. 'g ++ maxmain.cpp -o maxmain' –
Sie müssen die Namen aller .cpp-Dateien beim Kompilieren oder Verknüpfen von Objekten nach dem separaten Kompilieren angeben. –