2010-08-05 2 views
3

정적 및 동적 라이브러리에 대해 읽었습니다. 탐구에 더 많은 나는 내가 만든 세 개의 파일이 .cpp 파일과 이제 1 개 .h 파일을 동적 라이브러리가 사용될 때 정의되지 않은 참조 문제

main.cpp

#include "demo.h" 

int main() 
{ 

    demo d; 
    demo d1=d; 
    demo d2; 
    d2=d; 
} 

demo.h

class demo 
{ 

    int a; 

    public: 

    demo(); 
    demo(const demo&); 
    demo& operator=(const demo&); 
    ~demo(); 
}; 

demo.cpp

#include "demo.h" 
#include <iostream> 
demo::demo():a() 
{ 
    std::cout<<"\nInside default constructor\n"; 
} 

demo::demo(const demo&k) 
{ 

    this->a=k.a; 
    std::cout<<"\nInside copy constructor\n"; 
} 

demo& demo::operator=(const demo&k) 
{ 
    this->a=k.a; 
    std::cout<<"\nInside copy assignment operator\n"; 
    return *this; 
} 

demo::~demo() 
{ 
    std::cout<<"\nInside destructor\n"; 
} 
생성 두 개의 오브젝트 파일 : 다음 g++ -c demo.cppg++ -c main.cpp을 사용하고 demo.omain.o은 실행 모든 것을 만들 내 정적 라이브러리 ( g++ demo.a -o demo)를 사용할 때 ar cr demo.a demo.o main.o

가 나는 또한 지금 g++ -shared demo.o main.o -o demo.dll

를 사용하여 동적 라이브러리를 사용하여 만든 정적 라이브러리를 생성 잘 간다. 그러나 동적 라이브러리를 사용하여 실행 파일을 만들면 오류가 발생합니다. Undefined reference to main 다음 명령을 사용하여 실행 파일 g++ demo.dll -o demo을 생성했습니다.

g++ main.cpp -o demo demo.dll을 사용하면 모든 것이 잘됩니다. 이유가 무엇입니까?

어디서 잘못 되었나요?

+0

그것은 나를 위해 작동합니다. makefile을 사용한다면 게시 할 수 있습니까? 그리고 helloWorld 나'int main() {return (0);} '과 같은 공유 라이브러리에서 더 간단한 것을 만들려고 할 때 어떻게됩니까? – Beta

답변

1

.so (또는 .dll) 코드를 컴파일 할 때 해당 코드는 위치 독립적이어야합니다. 남자 GCC : 즉

-shared 
     Produce a shared object which can then be linked with other objects 
     to form an executable. Not all systems support this option. For 
     predictable results, you must also specify the same set of options 
     that were used to generate code (-fpic, -fPIC, or model suboptions) 
     when you specify this option. 

    ... 

    -fpic 
     Generate position-independent code (PIC) suitable for use in a 
     shared library, if supported for the target machine. Such code 
     accesses all constant addresses through a global offset table 
     (GOT). The dynamic loader resolves the GOT entries when the 
     program starts (the dynamic loader is not part of GCC; it is part 
     of the operating system). If the GOT size for the linked 
     executable exceeds a machine-specific maximum size, you get an 
     error message from the linker indicating that -fpic does not work; 
     in that case, recompile with -fPIC instead. (These maximums are 8k 
     on the SPARC and 32k on the m68k and RS/6000. The 386 has no such 
     limit.) 

     Position-independent code requires special support, and therefore 
     works only on certain machines. For the 386, GCC supports PIC for 
     System V but not for the Sun 386i. Code generated for the IBM 
     RS/6000 is always position-independent. 

     When this flag is set, the macros "__pic__" and "__PIC__" are 
     defined to 1. 

는 :

g++ -o main.o -c -fpic main.cpp 
g++ -o demo.o -c -fpic demo.cpp 
g++ -o demo.dll -shared main.o demo.o 
g++ -o demo demo.dll