简体   繁体   English

C ++如何将主类与头文件链接?

[英]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.cppmain()的定义,因为尝试在一个可执行文件的全局名称空间中放置多个非静态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.

相关问题 如何在我的主程序c ++中使用我自己制作的Array头文件? - How can I use my own made Array header file in my main program c++? 如何在C ++中将头文件中的初始化变量导出到main.cpp文件中? - How do I export an initialized variable from a header file to my main.cpp file in C++? 我如何获取和使用头文件<graphics.h>在我的 C++ 程序中? - How I can get and use the header file <graphics.h> in my C++ program? 在设计我的 ZF20E3C5E54C0AB3D375D866F 时,我是否应该在我的 C++ header 文件中完全隐藏内部 class? - Should I totally hide the internal class in my C++ header file when designing my SDK? 如果标头,类和主目录不在同一个文件夹中,如何运行c ++文件? - how to run c++ file if header, class, and main are not in the same folder? 我可以在 C++ header 文件中添加主 function 吗? - Can I add main function in C++ header file? 如何正确定义 C++ class 析构函数并将其链接到主文件? - How to correctly define and link a C++ class destructor to a main file? 在我的主文件中全局创建C ++类实例 - Creating C++ class instances globally within my main file 我的 main() 文件中不能包含 header 文件 - I can't include header files in my main() file 如何找到我的C ++类的实际大小? - How can I find the real size of my C++ class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM