Reputation: 321
This is as basic as it gets but I have a header file Test.h with a function prototype. Then a source code file with the function definition, Test.cpp. Lastly I have my Main.cpp file that calls the function in Test.cpp. The problem is that I get an error in Main.cpp stating that function1 is undefined. Can you see what I'm doing wrong?
Test.h
int function1(int);
Test.cpp
#include "Test.h"
#include <iostream>
int main(){
}
int function1(int i){
std::cout << "fuction1(" << i << ")" << std::endl << "Returns: 1" << std::endl;
return 1;
}
Main.cpp
#include <iostream>
#include "Test.h"
int main(){
function1(5);
}
Also Test.cpp didn't compile until I added a main() function. I'm pretty fluent in java and this seems to contradict my thinking. In java I would only have one main method which is found in my main class. Other classes have a constructor. Please help me make this connection from java to c++.
Upvotes: 1
Views: 6169
Reputation: 75062
You have to tell the compiler what it should link.
Firstly, remove the definition of main()
in test.cpp
because trying to put multiple non-static main()
in global namespace in one executable will lead to link error.
Then, use your compiler properly. For example, if you use GCC,
g++ -o Main Main.cpp Test.cpp
or
g++ -c -o Main.o Main.cpp
g++ -c -o Test.o Test.cpp
g++ -o Main Main.o test.o
Upvotes: 6