[SOLVED] How do I make my header, function and main file work together, I always get: error: Id returned 1 exit status

Issue

I made a very simple C++ program where the goal is to use functions in different files. The function justs prints out a certain message passed in a parameter. 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:

  • main.cpp (main file)
  • simple.h (header file (function definition))
  • simple.cpp (function file)

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

#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED

#include <string>

void message(std::string message);

#endif

simple.cpp

#include "simple.h"

void message(std::string message){
    cout << message;
}

Solution

I was use visual studio 2019 to compile your code. First compile error 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
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include<iostream>
#include <string>

void message(std::string message);

#endif
  • simple.cpp
#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.

Answered By – HenryTien

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.