0

I was writing a very basic C++ project in CodeBlocks. I have the following files in the source directory:

add.cpp

#include <iostream>

using namespace std;

void add(void);


void add(void)
{
    int num1, num2, sum;

    cout << "Enter 2 numbers : " << endl;
    cin >> num1 >> num2;

    sum = num1 + num2;

    cout << "\n";
    cout << "Sum = " << sum << endl;
}

sayhello.cpp

#include <iostream>

void sayhello(void);


void sayhello(void)
{
    std::string str;

    std::cout << "Tell me your name : ";
    std::cin >> str;

    std::cout << std::endl << "Hello Mr./Ms. " << str << "! Welcome to C++!";
}

main.cpp

#include <iostream>

using namespace std;


int main(void)
{
    sayhello();
    add();

    return 0;
}

But executing the main() throws the error error 'sayhello' was not declared in this scope. What am I doing wrong here? I am new to C++ and this is my first project.

skrowten_hermit
  • 437
  • 3
  • 11
  • 28
  • For an easy fix, move the declarations (`void add(void);` and `void sayhello(void);`) to main.cpp. – HolyBlackCat Sep 17 '19 at 14:00
  • Great! It worked. Can you explain what happens there in an answer if you could? – skrowten_hermit Sep 17 '19 at 14:04
  • 2
    I can't add an answer since the question is closed. In short, you have to declare functions before using them. Declaration visiblity is limited to one translation unit (aka the .cpp file with the headers it includes), so you need to declare the functions in each TU that uses them. Your C++ book probably has a more detailed explanation. – HolyBlackCat Sep 17 '19 at 14:09

0 Answers0