c++cnetwork-programmingsolarissunstudio

Linking Error in Sun Studio 10 under Solaris


I wrote a test program like this:

#include <sys/socket.h>
int main( void ) {
    int  sock = socket(AF_INET, SOCK_DGRAM, 0);
    return 0;
}

And tried to compile it:

$ /tool/sunstudio/bin/cc test.c
Undefined                       first referenced
 symbol                             in file
socket                              test.o
ld: fatal: Symbol referencing errors. No output written to a.out

The output is "symbol socket is not referenced".

Kindly give me the direction so that I can resolve this.


Solution

  • Here's the question.

    I wrote a test program like this:

    #include <sys/socket.h>
    int main( void ) {
        int  sock = socket(AF_INET, SOCK_DGRAM, 0);
        return 0;
    }
    

    And tried to compile it so (this is the output that really helps, you have to remember that modern compilers really try their best to help you fix any problems):

    $ /tool/sunstudio/bin/cc test.c
    Undefined                       first referenced
     symbol                             in file
    socket                              test.o
    ld: fatal: Symbol referencing errors. No output written to a.out
    

    Now, from the output we can see that the symbol socket is not referenced. So if you type man socket you will get the following from the man page:

    SYNOPSIS
         cc [ flag ... ] file ... -lsocket  -lnsl  [ library ... ]
    

    The -l flag indicates that to use this function you need to also link the named library. In this case you are being told to add -lsocket -lnsl to the cc command line as follows:

    $ /tool/sunstudio/bin/cc test.c -lsocket -lnsl