Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

gcc - How to compile C++ under Ubuntu Linux?

I cut&pasted the below code from a previous question into a file called "avishay.cpp" and then ran

gcc avishay.cpp

only to get the following error messages from the linker. What went wrong, what should I have done?

carl@carl-ubuntu:~/Projects/StackOverflow$ gcc -static avishay.cpp 
/tmp/cccRNW34.o: In function `__static_initialization_and_destruction_0(int, int)':
avishay.cpp:(.text+0x41): undefined reference to `std::ios_base::Init::Init()'
avishay.cpp:(.text+0x46): undefined reference to `std::ios_base::Init::~Init()'
/tmp/cccRNW34.o: In function `A::func()':
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x11): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x16): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x36): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x3b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(int)'
/tmp/cccRNW34.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

The C++ code (not my code, I was just trying to run it):

#include <iostream>
using namespace std;

class A
{
private:
   int _dmember;

public:
   void func()
   {
     cout<<"Inside A!! "<<endl;
     cout<<_dmember; // crash when reach here.
   }
};

int main ()

{

    A* a= NULL;

    a->func(); // prints "Inside A!!!" 

    return 1;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use g++, not gcc, to compile C++ programs.

For this particular program, I just typed

make avishay

and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...