Search code examples
c++linkerlibav

Undefined symbols in libav when compiling as C++, but not as C


I am trying to compile some simple code using the libav libraries.

// Some simple code to demonstrate
#include <libavformat/avformat.h>

int main(int argc, char *argv[]) {
    av_register_all();
    return 0;
}

I'm on a Mac, with gcc version 4.2.1.

When I try to compile the code as C using

gcc -o main main.c -lavformat

then the code compiles and links fine. However, when I try to compile it as C++ using

g++ -o main main.cpp -lavformat

it gives me undefined symbols errors:

Undefined symbols for architecture x86_64:
  "av_register_all()", referenced from:
      _main in ccQ23HMe.o

When I run with the -v option, the linking steps run are:

// gcc
"/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.8.0 -o c
 /var/folders/r0/n22t1hyn7ts92jxgd9_pn8yw0000gn/T/main-uUfZkM.o -lavformat
-lSystem /usr/bin/../lib/clang/4.1/lib/darwin/libclang_rt.osx.a

// g++
"/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.8.0 -o c
 /var/folders/r0/n22t1hyn7ts92jxgd9_pn8yw0000gn/T/main-5QU6fj.o -lavformat
 -lstdc++ -lSystem /usr/bin/../lib/clang/4.1/lib/darwin/libclang_rt.osx.a

Here, the only difference is the addition of -lstdc++ to the linking.

Why are these undefined symbol errors appearing? Is there some reason that simply adding a library to the linking would cause these undefined symbols? Or is there something else that is causing this problem, perhaps specifically related to libavformat?


Solution

  • The libav "Frequently Asked Questions" list covers this exact scenario!

    Here, the only difference is the addition of -lstdc++ to the linking.

    Nope — that, and you're using a different language with different default calling conventions.

    av_register_all as declared in the header is not marked extern "C", whereas the definition in the actual compiled library requires good old-fashioned C calling convention.

    Surround your libav includes with extern "C".