-1

I created a C++ Class called Blue and a function within that class called void drawblueline() I'm new to programming but thought I would call this in my command line by writing

int main( )
{

Blue blue; 
blue.drawblueline();
}

I'm getting two linker errors on blue.draw.. if there's nothing wrong with how I called it then maybe the mistake is in the function?

Andrea F
  • 721
  • 2
  • 9
  • 16

2 Answers2

1

If you implement class methods in somefile.cpp and your program is in otherfile.cpp you need to compile it by g++ somefile.cpp otherfile.cpp ....

Linker error means that you included all headers you need, but you didn't compile definition of some functions.

The best way to compile more complex projects is through Makefile.

Example Makefile:

all: main

main: main.cpp blue.o
    g++ main.cpp blue.o -o main

blue.o: blue.cpp blue.h
    g++ blue.cpp -c -o blue.o

Then you can compile your project by command make

This makefile says that your projects needs main, main depends on main.cpp and blue.o. So if main.cpp or blue.o is not actual it would tries to make both of them and then main, by command g++ main.cpp blue.o -o main.

Then, blue.o depends on blue.cpp and blue.h. Blue would be compiled to object file blue.o.

Ari
  • 3,103
  • 1
  • 25
  • 48
  • Thanks for the help! I'm using XCode. you wouldn't by any chance know about compiling in that environment? thought it did it for you:/ – Andrea F Jul 26 '13 at 08:12
  • @AndreaF as far as I know in this environment you need to add all source files to project. Make sure all source files are shown under `Compile Sources`. – Ari Jul 26 '13 at 08:16
1

Make sure you included all the required header files in your main.cpp file, also you compiled and linked all the dependencies(.cpp files) before running your application.

For example you have two files named First.cpp and Second.cpp and Main.cpp, First you have to compile First.cpp ,Second.cpp then Main.cpp, Now you have to link them to resolve all the references.

If you are using Ubuntu or similar OS's this line will compile and link at the same time

g++ First.cpp Second.cpp Main.cpp -o Bluerectangle

The above line compiles then links all the files and creates an object file named Bluerectangle.

To run it type Bluerectangle in the terminal.

Mahesh
  • 1,115
  • 1
  • 6
  • 19