-3

I'd like to declare a function in my main.cpp, so that my main function can be the first one in the file. It looks like this:

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;
}

However, when compiling I get an error:

/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]

What is wrong?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
PonasM
  • 163
  • 2
  • 8
  • 3
    `myfunction` and `my_function` are not the same. – ducminh Aug 18 '18 at 17:32
  • Then please [edit] your post. – Ron Aug 18 '18 at 17:33
  • 4
    Declaration should match definition. – Evg Aug 18 '18 at 17:34
  • typo: change `string my_function(string message = "");` and `string my_function(string message) { your_logic }` – eyllanesc Aug 18 '18 at 17:35
  • 1
    The forum appears to be plagued with drive-by downvoting without explanation. I suspect some of the downvoting is done by bots. – Eljay Aug 18 '18 at 17:50
  • 2
    @PonasM I am not the downvoter but was close to becoming one because: this is basic knowledge and is expected of you to cover that part as SO is not a place where you learn a language. Cover the basics first. A good place to start would be these [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). And then come back with a specific problem you are facing. – Ron Aug 18 '18 at 17:58
  • 2
    I also didn't downvote. But the downvote button is for "lack of research". There are hundreds of examples and tutorials on the net showing and explaining "how functions work". – Galik Aug 18 '18 at 18:13

3 Answers3

4

string my_function(); is declared but is not defined.

It should be:

string my_function(string message = "");

...

string my_function(string message) { ... }
Evg
  • 25,259
  • 5
  • 41
  • 83
1

Better:

  • Make default parameters in the declaration, but not the definition.

  • Pass strings by const reference so you don't incur an unnecessary copy of the string.

Updated:

string my_function(const string& message = "");

int main() {
    my_function();
    return 0;
}

string my_function(const string& message) {
    string response;
    cout << message;
    getline(cin, response);
    return response;
}
selbie
  • 100,020
  • 15
  • 103
  • 173
  • In this particular case it is just 7 more characters to type. In general case - agree. And don't forget `std::string_view`. – Evg Aug 18 '18 at 17:41
0

You can use the following solution:

string my_function(string message = "");

...

string my_function(string message)
 {
    your codes here
 }
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Shani
  • 1
  • 3