C ++ class why do we need main?

Hello, I am writing a small project in C ++ where I would like some classes to do some work, I wrote interfaces and class implementations.

What surprises me is that I cannot have a simple class without main (), I would like to have a class that was once created, methods can be called, do something, but I don't need (and want) main ( ) in the implementation of the class. Here is an example that I have in my head of what I would like to have:

file animal.h:

class animal
{
 public: 
   animal();
  ~animal();

 public:
   int method1(int arg1);

 private:
   int var1;
};

file animal.cpp:

#include "animal.h"

animal::animal(){...}
animal::~animal(){...}
int animal::method1(int arg1){return var1;}
}

And I would like to name the animal class another file and make it work, something like this: The app.cpp file:

#include <neededlib>
#include "animal.h"

int main()
{
 animal dog;
 cout << dog.method1(42);
 return 0;
}

But the compiler gave me

/usr/lib/gcc/i686-pc-linux-gnu/4.3.3/../../../crt1.o: In function _start:

"(.text+0x18): undefined reference to `main`"

collect2: ld returned 1 exit status 

for animal.cpp, but I don’t need the main one there, or do I need it?

Where am I mistaken?

+1
source share
5 answers

( ) main() .

main - . . .

< undefined " animal.cpp, , ?

: app.cpp animal.cpp.

Make , - g++ animal.h -o animal g++ animal.cpp,

. : g++ animal.h

animal.cpp , g++ . app.cpp, main. app.cpp animal. , , , main, , .

g++ , . - :

g++ animal.cpp app.cpp -o test

test, , :

./test
+19

-, : animal dog = new animal();

animal * dog = new animal();
cout << dog->method1(42);
delete animal;

animal dog;

-, , .cpp.

gcc -o animal animal.cpp app.cpp 

, gcc.

+6

You must compile them together (in a single command g++) or compile both of them into object files ( g++ -c), and then use them ldto link the object files together.

Example Makefile:

all: app.exe

app.exe: app.o animal.o
    g++ -o app.exe app.o animal.o

app.o: app.cpp
    g++ -c -o app.o app.cpp

animal.o: animal.cpp animal.h
    g++ -c -o animal.o animal.cpp
+4
source
class animal
{
 public: 
   animal();
  ~animal();

 public:
   method1(int arg1);

 private:
   int var1;
};

Note that you did not put a semicolon at the end of the class declaration. C ++ requires this and sometimes gives confusing / misleading error messages if you forget it.

+1
source
 public:
   method1(int arg1);

You do not need the return type of method method1. Did you mean something like

   int method1(int arg1);
0
source

All Articles