66

I have a static library file called libunp.a, I do know I could use gcc -lunp xx to link to the library.

I could use #pragma comment(lib,"xxx.lib") to tell the Microsoft C/C++ compiler to include the library; how could I do it under Linux/GCC?

Jichao
  • 40,341
  • 47
  • 125
  • 198

3 Answers3

30

There doesn't seem to be any mention of any equivalent pragmas in the GCC manual's page on pragmas.

One reason I saw for GCC not supporting linking in source code was that sometimes, correct linking depends on link order; and this would require you to make sure that the linking order happens correctly no matter the order of compilation. If you're going to go to that much work, you may as well just pass the linker arguments on the command line (or otherwise), I suppose.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 3
    Same applies for some, if not all Windows compilers. But yes, such pragmas are __bad__ –  Nov 06 '09 at 03:37
  • 7
    "correct compilation depends on link order." -- No, as the linked article states, correct LINKING depends on link order. – Windows programmer Nov 06 '09 at 03:39
  • Depending on the order is sometimes a good thing for the linking, but it should not disallow *specifying something actually not depending on any specific linking order* (except the order to the system libraries which always come later). In particular, it is just stupid to rule out the cases with only one external library for this reason. It is generally unsound for C/C++ folks as it is like to say, "hey, we don't like undefined/unspecified behavior, so let's make all of them well-defined!" – FrankHB Nov 24 '20 at 19:48
21

Libraries should be specified during the linking step. Such information simply doesn't belong inside a translation unit. A translation unit can be preprocessed, compiled and assembled even without a linking stage.

Simply because #pragma comment(lib,"xxx.lib") is in the source file does not mean the compiler consumes it. In fact, it goes in as a comment and is subsequently used by the linker. Not much different than *nix.

jww
  • 97,681
  • 90
  • 411
  • 885
Jeffrey Walton
  • 255
  • 2
  • 4
  • 2
    You are not entirely right, there are some cases like using ROOT (root.cern.ch) where this could be very helpful. – RSFalcon7 Mar 21 '13 at 01:53
  • OP clearly figured that much already, the GCC linker doesn't understand that pragma. This in no way answers the question. – rustyx Jun 10 '20 at 09:42
0

Use this GCC flag to generate an error for unknown pragmas. It will quickly tell you if the compiler understands it.

-Werror=unknown-pragmas

  • 5
    This answer does not answer the question. – user202729 Dec 05 '18 at 11:16
  • 2
    ...and no, GCC 9.2 or clang 8 still do not understand this pragma (e.g. `warning: ignoring #pragma comment [-Wunknown-pragmas] \\ #pragma comment(lib,"xxx.lib")`) – alfC Oct 24 '19 at 06:50