首页 > 解决方案 > 如何在 C++ 中正确声明函数?

问题描述

我想在 my 中声明一个函数main.cpp,这样我的main函数就可以成为文件中的第一个函数。它看起来像这样:

main.cpp

 #include <iostream>
 #include <string>
 using namespace std;

string my_function();
int main () {
    my_function();
    return 0;
}
string my_function(string message = "") {
    string response;
    cout << message;
    getline(cin,response);
    return response;
}

但是,编译时出现错误:

/usr/bin/ld: /tmp/cco8jyj1.o: in function `main':
main.cpp:(.text+0x1f): undefined reference to `my_function[abi:cxx11]()'
collect2: error: ld returned 1 exit status
[Finished in 1.4s with exit code 1]

怎么了?

标签: c++

解决方案


string my_function();已声明但未定义。

它应该是:

string my_function(string message = "");

...

string my_function(string message) { ... }

推荐阅读