Why is my HelloWorld function not declared in this scope?

#include <iostream>

using namespace std;

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

void HelloWorld()
{
    cout << "Hello, World" << endl;
}

I am getting the following compilation error with g++:

l1.cpp: In function 'int main()':
l1.cpp:5:15: error: 'HelloWorld' was not declared in this scope

Solution 1:

You need to either declare or define the function before you can use it. Otherwise, it doesn't know that HelloWorld() exists as a function.

Add this before your main function:

void HelloWorld();

Alternatively, you can move the definition of HelloWorld() before your main():

#include <iostream>
using namespace std;

void HelloWorld()
{
  cout << "Hello, World" << endl;
}

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

Solution 2:

You must declare the function before you can use it:

#include <iostream>

using namespace std;

void HelloWorld();

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

void HelloWorld()
{
    cout << "Hello, World" << endl;
}

or you can move the definition of HelloWorld() before main()

Solution 3:

You need to forward declare HelloWorld() so main knows what it is. Like so:

#include <iostream>
using namespace std;
void HelloWorld();
int main()
{
  HelloWorld();
  return 0;
}
void HelloWorld()
{
  cout << "Hello, World" << endl;
}