Page 97 - C-Language
P. 97

{
             return 5;
         }

         int main(int argc, char **argv)
         {
             int foo_val;
             foo_val = foo();
             return foo_val;
         }


        Now this code will compile. An alternative situation arises where the source for foo() is in a
        separate source file foo.c (and there's a header foo.h to declare foo() that is included in both foo.c
        and undefined_reference.c). Then the fix is to link both the object file from foo.c and
        undefined_reference.c, or to compile both the source files:


         $ gcc -c undefined_reference.c
         $ gcc -c foo.c
         $ gcc -o working_program undefined_reference.o foo.o
         $


        Or:


         $ gcc -o working_program undefined_reference.c foo.c
         $


        A more complex case is where libraries are involved, like in the code:


         #include <stdio.h>
         #include <stdlib.h>
         #include <math.h>

         int main(int argc, char **argv)
         {
             double first;
             double second;
             double power;

             if (argc != 3)
             {
                 fprintf(stderr, "Usage: %s <denom> <nom>\n", argv[0]);
                 return EXIT_FAILURE;
             }

             /* Translate user input to numbers, extra error checking
              * should be done here. */
             first = strtod(argv[1], NULL);
             second = strtod(argv[2], NULL);

             /* Use function pow() from libm - this will cause a linkage
              * error unless this code is compiled against libm! */
             power = pow(first, second);

             printf("%f to the power of %f = %f\n", first, second, power);

             return EXIT_SUCCESS;




        https://riptutorial.com/                                                                               73
   92   93   94   95   96   97   98   99   100   101   102