0

when trying to compile a .cpp file called rat with a .h file called normalize which is located in a different folder (rat.h is in the same folder as rat.cpp) , I'm typing

g++ -I/opt/cis/include/ -I/opt/cis/lib/ rat.cpp

I have included an int main () in the .cpp file itself, and have completely commented out the inner workings of the .h file and the .cpp file just to try to compile correctly.

The .h file (commented items not included)

  1 #ifndef RAT_H
  2 #define RAT_H
  3 #include <iostream>
  4 #include <string>
  5 
  6 class Rat {
  7         friend std::ostream &operator<<(std::ostream &, const Rat &);
  8         friend std::istream &operator>>(std::istream &, Rat &);
  9         private:
 10                 double n,d;
 11         public: 
 12                 Rat(): n(0), d(1) {}
 13 };
 14. #endif

The .cpp file

  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <string>
  4 #include <sstream>
  5 #include "rat.h"
  6 #include "normalize.h"
  7 using namespace std;
  8 #ifdef TEST_RAT
  9 int main() {};
  10 #endif

What am I doing incorrectly? Sorry if it is obvious.

dward4
  • 1,615
  • 3
  • 15
  • 30

5 Answers5

4

Your main function exists only if the macro TEST_RAT is defined. Either:

  • add -DTEST_RAT to your compiler CFLAGS
  • add the line #define TEST_RAT before the #ifdef
  • remove the #ifdef TEST_RAT and #endif pair in your .cpp
Bruno Ferreira
  • 1,621
  • 12
  • 19
0

you forgot :

#define TEST_RAT

This is not defined in your code so this should work now.

user2076694
  • 806
  • 1
  • 6
  • 10
0

Since you put your main() in an #ifdef it is left out if TEST_RAT is not defined. Since it isn't you don't have a main so you cannot create an executable (there is no point of entry) and g++ fails with the error seen.

clcto
  • 9,530
  • 20
  • 42
0

Most likely you wanted to put this in your main (to make sure the Rat class is defined):

    #ifdef RAT_H
    int main() {};
    #endif
IonutG
  • 51
  • 2
0

Another option, since no-one's mentioned it yet, is the -c flag:

g++ -c -I/opt/cis/include/ -I/opt/cis/lib/ rat.cpp

This will compile rat.cpp to an object file rat.o without attempting to link it into a program (and so require a main).

If you're testing for correctness you might also want to try -W or -Wall for warnings.

Rup
  • 33,765
  • 9
  • 83
  • 112
  • -c compiles and outputs the file to an object file. If you want only to test if it compiles, you may also add the `-o /dev/null` option – Bruno Ferreira Apr 22 '14 at 17:17