1
votes

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++.

1
"Can you see what I'm doing wrong?" No because you didn't show us how you use your compiler.MikeCAT
I had no issues compiling Test.cpp without the utterly superflous main(). You are not showing everything you're doing, in this question. After removing main() from Test.cpp, there's absolutely nothing wrong with the shown code. Therefore, what's wrong must be with the code and/or additional files/scripts that you have not shown.Sam Varshavchik
@MikeCAT I'm using codeblocks IDE. With which there's an automatic build button. By your comment I'm assuming I have to make a makefile to specify how the compilation should be done?Vindictive
@Vindictive I guess you are trying to compile a single file and you should create a "project" to compile and link multiple files.MikeCAT
You have to tell your IDE that your project consists of two translation units. I am not familiar with that IDE, so I can't tell you how; but it looks like you're just trying to build two separate translation units, in the IDE, independently of each other, while you need to configure your IDE so that it knows that both translation units is one project.Sam Varshavchik

1 Answers

6
votes

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