0

On a Ubuntu Linux machine g++ doesn't appear to be linking libraries as it should. I can't supply full source code, but essentially it is a small program which creates a pthread. It compiles fine on two other Debian machines, but on the Ubuntu machine it complains about an undefined reference to pthread_create.

The command line is something like this:

g++ -I. -lpthread source_code.cpp -o program

To debug this I ran g++ under strace to see how it was looking for libpthread. When I did that, I did not see ANY references to libpthread. It was as if the linker wasn't even trying to search for the library. On the machines that did compile I saw several calls to open() when it searched the filesystem for the library.

When I ran ld separately it seems to find libpthread without a problem, and the strace output confirms that it is searching for the library as it should. I ran ld separately like this:

user@machine:~/src$ ld -lpthread
ld: warning: cannot find entry symbol _start; not setting start address

Why could cause g++ to not search the filesystem correctly for libraries when ld seems to do so just fine by itself? Kinda stumped on this one at the moment.

Thanks!

Mr. Shickadance
  • 5,283
  • 9
  • 45
  • 61
  • 1
    Linking is order dependent. Did you try putting `-lpthread` at the END if your compile line? – Fred Larson Feb 12 '15 at 17:28
  • @FredLarson That seemed to be the trick. I knew that linker order matter under certain situations, but this one threw me for a loop. Apparently its a part of an actual effort to implement more strict behavior in GCC. Can you add an answer that I can accept? Thanks! – Mr. Shickadance Feb 13 '15 at 18:59
  • Actually, I think @Slava gave a better answer. See this: http://stackoverflow.com/q/2127797/10077 – Fred Larson Feb 13 '15 at 19:20

1 Answers1

1

For enabling multithreading in gcc you should pass -pthread flag not -lpthread -

-pthread

       Add support for multithreading using the POSIX threads library.                
       This option sets flags for both
       the preprocessor and linker.  
       It does not affect the thread safety of object code produced by the
       compiler or that of libraries supplied with it.
Community
  • 1
  • 1
Slava
  • 43,454
  • 1
  • 47
  • 90
  • Why not just link the library directly? Is there any rationale for this? – Mr. Shickadance Feb 13 '15 at 19:00
  • @Mr.Shickadance because `-pthreads` not only links library but also set flags for the preprocessor so some library headers may compile differently. – Slava Feb 17 '15 at 15:00