Page 98 - C-Language
P. 98

}


        The code is syntactically correct, declaration for pow() exists from #include <math.h>, so we try to
        compile and link but get an error like this:


         $ gcc no_library_in_link.c -o no_library_in_link
         /tmp/ccduQQqA.o: In function `main':
         no_library_in_link.c:(.text+0x8b): undefined reference to `pow'
         collect2: error: ld returned 1 exit status
         $


        This happens because the definition for pow() wasn't found during the linking stage. To fix this we
        have to specify we want to link against the math library called libm by specifying the -lm flag. (Note
        that there are platforms such as macOS where -lm is not needed, but when you get the undefined
        reference, the library is needed.)


        So we run the compilation stage again, this time specifying the library (after the source or object
        files):


         $ gcc no_library_in_link.c -lm -o library_in_link_cmd
         $ ./library_in_link_cmd 2 4
         2.000000 to the power of 4.000000 = 16.000000
         $


        And it works!


        Misunderstanding array decay


        A common problem in code that uses multidimensional arrays, arrays of pointers, etc. is the fact
        that Type** and Type[M][N] are fundamentally different types:


         #include <stdio.h>

         void print_strings(char **strings, size_t n)
         {
             size_t i;
             for (i = 0; i < n; i++)
                 puts(strings[i]);
         }

         int main(void)
         {
             char s[4][20] = {"Example 1", "Example 2", "Example 3", "Example 4"};
             print_strings(s, 4);
             return 0;
         }


        Sample compiler output:


         file1.c: In function 'main':
         file1.c:13:23: error: passing argument 1 of 'print_strings' from incompatible pointer type [-
         Wincompatible-pointer-types]




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