it-source

정적 C 라이브러리를 C++ 코드와 연결할 때 "정의되지 않은 참조" 오류 발생

criticalcode 2023. 6. 20. 21:40
반응형

정적 C 라이브러리를 C++ 코드와 연결할 때 "정의되지 않은 참조" 오류 발생

테스트 파일(링크 테스트용)이 있어 오버로드합니다.new/delete내 소유의 오퍼레이터들malloc/free호출된 라이브러리libxmalloc.a하지만 정적 라이브러리를 연결할 때 다음과 같은 "정의되지 않은 참조" 오류가 계속 발생합니다. 이 오류는 다음과 같습니다.test.o그리고.-lxmalloc하지만 모든 것이 이 도서관을 연결하는 다른 C 프로그램과 잘 작동합니다.저는 이 문제에 대해 매우 혼란스럽고 어떤 단서라도 감사합니다.

오류 메시지:

g++ -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64 -c -o test.o test.cpp
g++ -m64 -O3 -L. -o demo test.o -lxmalloc
test.o: In function `operator new(unsigned long)':
test.cpp:(.text+0x1): undefined reference to `malloc(unsigned long)'
test.o: In function `operator delete(void*)':
test.cpp:(.text+0x11): undefined reference to `free(void*)'
test.o: In function `operator new[](unsigned long)':
test.cpp:(.text+0x21): undefined reference to `malloc(unsigned long)'
test.o: In function `operator delete[](void*)':
test.cpp:(.text+0x31): undefined reference to `free(void*)'
test.o: In function `main':
test.cpp:(.text.startup+0xc): undefined reference to `malloc(unsigned long)'
test.cpp:(.text.startup+0x19): undefined reference to `malloc(unsigned long)'
test.cpp:(.text.startup+0x24): undefined reference to `free(void*)'
test.cpp:(.text.startup+0x31): undefined reference to `free(void*)'
collect2: ld returned 1 exit status
make: *** [demo] Error 1

나의test.cpp파일:

#include <dual/xalloc.h>
#include <dual/xmalloc.h>
void*
operator new (size_t sz)
{
    return malloc(sz);
}
void
operator delete (void *ptr)
{
    free(ptr);
}
void*
operator new[] (size_t sz)
{
    return malloc(sz);
}
void
operator delete[] (void *ptr)
{
    free(ptr);
}
int
main(void)
{
    int *iP = new int;
    int *aP = new int[3];
    delete iP;
    delete[] aP;
    return 0;
}

나의Makefile:

CFLAGS += -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64
CXXFLAGS += -m64 -O3
LIBDIR += -L.
LIBS += -lxmalloc
all: demo
demo: test.o
    $(CXX) $(CXXFLAGS) $(LIBDIR) -o demo test.o $(LIBS)
test.o: test.cpp
$(CXX) $(CFLAGS) -c -o $@ $<
clean:
- rm -f *.o demo

하지만 모든 것이 이 도서관을 연결하는 다른 C 프로그램과 잘 작동합니다.

C와 C++ 컴파일이 객체 파일 수준에서 서로 다른 기호 이름을 생성한다는 것을 눈치챘습니까?그것은 '이름 망글링'이라고 불립니다.
(C++) 링커는 정의되지 않은 참조를 오류 메시지에 디망글 기호로 표시하여 혼동을 일으킬 수 있습니다.검사하는 경우test.o로 철하다.nm -u참조된 기호 이름이 라이브러리에 제공된 이름과 일치하지 않습니다.

만약 당신이 플레인 C 컴파일러를 사용하여 컴파일된 외부로 링크된 함수들을 사용하고 싶다면, 당신은 그것들의 함수 선언들을 다음과 같이 동봉해야 할 것입니다.extern "C" {}내부에 선언되거나 정의된 모든 항목에 대해 C++ 이름 망글링을 억제하는 블록(예:

extern "C" 
{
    #include <dual/xalloc.h>
    #include <dual/xmalloc.h>
}

더 좋은 것은 다음과 같이 함수 선언을 머리글 파일로 묶을 수 있다는 것입니다.

#if defined (__cplusplus)
extern "C" {
#endif

/*
 * Put plain C function declarations here ...
 */ 

#if defined (__cplusplus)
}
#endif

언급URL : https://stackoverflow.com/questions/18877437/undefined-reference-to-errors-when-linking-static-c-library-with-c-code

반응형