2

I am stuck with the apparently common yet very cryptic compilation error

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I narrowed it down to a tiny implementation (from a tutorial) which just won't compile.

Header file: Num.h

class Num
{
 private:
 int num;
 public:
 Num(int n);
 int getNum();
}; 

Implementation: Num.cpp

#include "Num.h"
Num::Num(int n): num(n) {}
int Num::getNum()
{
 return num;
} 

Compilation command:

g++  Num.cpp

I don't see any obvious hints in the invocation stack (via g++ Num.cpp -v ).

Both Num.h and Num.cpp are located in the same directory, so I don't get why the linker wouldn't be able to link them. I suspect that I might need to set some environment variable, but which one?

Any help would be greatly appreciated! Thanks for your patience - I know this error has been posted here a thousand times before, but I haven't found an answer that works for me.

daenin
  • 21
  • 3
  • 3
    Not cryptic at all, compiler couldn't find the program entry point. – Mansoor Aug 24 '20 at 23:00
  • 1
    Everything is cryptic when you don't know the terminology. Easy decryption of the error messages will come with time, practice, and often reading, reading, and more reading. – user4581301 Aug 24 '20 at 23:08

2 Answers2

2

By default you need main function, from which program execution starts from there, to build executable binary file.

You can use -c option like

g++ -c Num.cpp

to do compilation only (no linking) and get an object file Num.o.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thanks for the super fast reply! Compiling without linking works indeed. However, I somehow need a way to compile the code _with_ linking because I'm using it as an include in a development tool that just compiles with g++ without giving the option to specify compile parameters. I also read about the need for a ```main``` so I tried adding a dummy one, but without success :-( header with main: ```class Num { private: int num; public: int _main(); Num(int n); int getNum(); }; ``` , implementation in .cpp ```int Num::_main(){}``` – daenin Aug 24 '20 at 23:09
  • int main() is can not be a class member function. It's must be a free function. Related: [https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main](https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main) – drescherjm Aug 24 '20 at 23:14
  • Thanks @drescherjm! Now it compiles with ```#include "Num.h" int main(){} Num::Num(int n): num(n) {} int Num::getNum() { return num; } ```Yay! – daenin Aug 24 '20 at 23:31
-1

For reference, solution was to add a dummy main to Num.cpp in order to compile with g++.

#include "Num.h" 
int main(){}  
Num::Num(int n): num(n) {} 
int Num::getNum() {  return num; }
daenin
  • 21
  • 3