ld linker error: undefined reference to `main'
in C++:
I know this question is about C, but if you stumble here and happen to be compiling in C++ (as was my case), it may be because you have your main()
function inside of a namespace. Move it outside the namespace and it will fix this error!
Ex:
will_not_run.cpp:
#include <iostream>
// <========== comment out the namespace (this lines plus the opening and
// closing braces) to make this program link!
namespace my_module
{
int main()
{
std::cout << "hello world!\n\n";
return 0;
}
} // namespace my_module
If you try to build and run with this command:
time g++ -Wall -Wextra -Werror -O3 -std=gnu++17 will_not_run.cpp \
-o will_not_run && will_not_run
...you'll get this error:
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status
To fix this, simply delete the namespace, or move main()
outside of it, and it works just fine again!
#include <iostream>
int main()
{
std::cout << "hello world!\n\n";
return 0;
}
So, if you need to access your my_module
namespace inside the main()
function, simply be explicit, and use it as my_module::my_func()
or whatever, or call using namespace my_module;
in whichever scope you'd like to have access to your namespaced content within your main()
function.