简体   繁体   中英

Am I using gcc wrong?

I've been having no end of trouble just getting started with C++. Seems like no matter what I do, I've got dozens of errors. I've taken to compiling example code from tutorials, but even the example code doesn't compile. For example, the code at: http://www.cppgameprogramming.com/cgi/nav.cgi?page=arrayclasses

gives me lots of flack when I try to:

$ g++ main.cpp -o dog

It says:

> main.cpp: In function 'int main()': main.cpp:18:15: warning: deleting
> array 'Dog myDogs [5]'
> C:\Users\bob-pc\Appdata\Local\Temp\ccTXXCOB.o:main.cpp:(.text+0x21):
> undefined rference to 'Dog::Dog()' C:\Users\bob-pc\Appdata\Local\Temp\ccTXXCOB.o:main.cpp:(.text+0x59):
> undefined rference to 'Dog::setAge(int)' C:\Users\bob-pc\Appdata\Local\Temp\ccTXXCOB.o:main.cpp:(.text+0x88):
> undefined rference to 'Dog::getAge()' collect2: Id returned 1 exit status

This isn't the first time I've tried straight copying example code & compiling it. I'm having lots of trouble even after I go over syntax, but I just can't seem to get headers & libraries working right. Any help much appreciated.

You have to include dog.cpp in the compilation:

g++ main.cpp dog.cpp -o dog

Alternatively, you can compile dog.cpp by itself to an object file, and include that in the final compilation:

g++ dog.cpp -c -o dog.o

g++ main.cpp dog.o -o dog

The example code is just plain wrong. :-)

//main.cpp
#include <iostream>
#include "Dog.h"

using namespace std;

int main()
{

    Dog myDogs[5];

    for (int i = 0; i <= 4; i++)
        myDogs[i].setAge( i * 2);

    for (int i = 0; i <= 4; i++)
        cout << "Dog number " << i << " is " << myDogs[i].getAge() << " years old!\n";

    delete [] myDogs;    <--- Don't do this!

    return 0;
}

You should not use delete if you have not used new to allocate the object. It this case the dogs will take care of themselves. Just remove the line with delete !

It is really hard to determine what is going on without taking a look at your code. Make sure you're including the .o of the file where the class dog is defined.

Also if the array wasn't created with new[], don't use delete[].

Finally, I know you're not specifically asking about this, but it may be worth it to find a better resource online to learn C++. At least use one that doesn't have embarrassing mistakes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM