[英]C++ how can I link my main class with my header file?
This is as basic as it gets but I have a header file Test.h with a function prototype. 这是最基本的,但是我有一个带有函数原型的头文件Test.h。 Then a source code file with the function definition, Test.cpp. 然后是带有功能定义Test.cpp的源代码文件。 Lastly I have my Main.cpp file that calls the function in Test.cpp. 最后,我有Main.cpp文件,该文件调用Test.cpp中的函数。 The problem is that I get an error in Main.cpp stating that function1 is undefined. 问题是我在Main.cpp中收到一条错误消息,指出function1未定义。 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 Main.cpp
#include <iostream>
#include "Test.h"
int main(){
function1(5);
}
Also Test.cpp didn't compile until I added a main() function. 另外,Test.cpp在我添加main()函数之前没有进行编译。 I'm pretty fluent in java and this seems to contradict my thinking. 我的Java很流利,这似乎与我的想法相矛盾。 In java I would only have one main method which is found in my main class. 在Java中,我只有一个在主类中找到的main方法。 Other classes have a constructor. 其他类具有构造函数。 Please help me make this connection from java to c++. 请帮助我建立从Java到C ++的连接。
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. 首先,删除test.cpp
中main()
的定义,因为尝试在一个可执行文件的全局名称空间中放置多个非静态main()
会导致链接错误。
Then, use your compiler properly. 然后,正确使用编译器。 For example, if you use GCC, 例如,如果您使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.