[英]How do I make my header, function and main file work together, I always get: error: Id returned 1 exit status
I made a very simple C++ program where the goal is to use functions in different files.我制作了一个非常简单的 C++ 程序,其目标是使用不同文件中的函数。 The function justs prints out a certain message passed in a parameter.
function 只是打印出在参数中传递的某个消息。 After some research, I read that for such project, I need 3 files: the main, the header and the function (apparently I shouldn't put the function code in the header file.) I now have three files:
After some research, I read that for such project, I need 3 files: the main, the header and the function (apparently I shouldn't put the function code in the header file.) I now have three files:
Whenever I try to make them work together, I always get the same error:每当我试图让它们一起工作时,我总是会遇到同样的错误:
C:\Users\juuhu\AppData\Local\Temp\ccQRa0R0.o:main.cpp:(.text+0x43): undefined reference to `message(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2.exe: error: ld returned 1 exit status
Here's the code of the three files:这是三个文件的代码:
main.cpp主文件
#include <iostream>
#include "simple.h"
using namespace std;
int main(){
message("Hello world!");
return 0;
}
simple.h简单的.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include <string>
void message(std::string message);
#endif
simple.cpp简单的.cpp
#include "simple.h"
void message(std::string message){
cout << message;
}
I was use visual studio 2019 to compile your code.我使用 Visual Studio 2019 编译您的代码。 First compile error output:"Error C2065 'cout': undeclared identifier message".
首先编译错误 output:"Error C2065 'cout': undeclared identifier message"。
When I add #include<iostream>
in simple.h and change simple.cpp message function the cout
to std::cout
, the program output "Hello world!"当我在 simple.h 中添加
#include<iostream>
并将 simple.cpp 消息 function cout
更改为std::cout
时,程序 output "Hello world!"
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include<iostream>
#include <string>
void message(std::string message);
#endif
#include "simple.h"
void message(std::string message) {
std::cout << message;
}
you can try again, hope you are successful to compile the code and get your to want.你可以再试一次,希望你成功编译代码并得到你想要的。
You haven't link the function defination file to the header file.您尚未将 function 定义文件链接到 header 文件。
simple.h简单的.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include <string>
#include "simple.cpp" // include the simple.cpp file
void message(std::string message);
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.