1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610
|
\input texinfo.tex @c -*- texinfo -*-
@c -*-texinfo-*-
@c This is the texinfo source for the manual "An Introduction to GCC".
@c Copyright (C) 2003, 2004, 2005 Network Theory Ltd
@c See the file COPYING.FDL for copying conditions.
@c @include config-local.texi
@c %**start of header
@setfilename gccintro.info
@settitle An Introduction to GCC
@c %**end of header
@iftex
@finalout
@end iftex
@setchapternewpage on
@c For installing properly under Debian packaging system
@dircategory Software development
@direntry
* gccintro: (gccintro). Introduction to GCC by Brian J. Gough.
@end direntry
@titlepage
@title An Introduction to GCC
@subtitle for the GNU Compilers @code{gcc} and @code{g++}
@subtitle Revised and updated for Debian
@author Brian Gough
@author Foreword by Richard M.@: Stallman
@page
Debian package version. 2012
The content of this Debian packaged version adds a chapter on ``Security
enhancement options'' and makes some minor file path adjustments to match
learning experiences under the Debian environment.
@vskip 0pt plus 1filll
@flushleft
Followings are the original page content.
A catalogue record for this book is available from the British Library.
Second printing, August 2005 (1/8/2005). Revised and updated.
First printing, March 2004 (7/3/2004).
Published by Network Theory Limited.
15 Royal Park
Bristol
BS8 3AL
United Kingdom
Email: info@@network-theory.co.uk
ISBN 0-9541617-9-3
Further information about this book is available from
@uref{http://www.network-theory.co.uk/gcc/intro/}
@end flushleft
@vskip 1ex
Cover Image: From a layout of a fast, energy-efficient hardware
stack.@footnote{``A Fast and Energy-Efficient Stack'' by J.@: Ebergen,
D.@: Finchelstein, R.@: Kao, J.@: Lexau and R.@: Hopkins.}
Image created with the free Electric VLSI design system by Steven Rubin
of Static Free Software
(@uref{http://www.staticfreesoft.com/,,www.staticfreesoft.com}). Static
Free Software provides support for Electric to the electronics design
industry.
@vskip 1ex
Copyright @copyright{} 2004, 2005 Network Theory Ltd.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with the Front-Cover Texts being ``A Network Theory
Manual'', and with the Back-Cover Texts as in (a) below. A copy of the
license is included in the section entitled ``GNU Free Documentation
License''.
(a) The Back-Cover Text is: ``The development of this manual was funded
entirely by Network Theory Ltd. Copies published by Network Theory Ltd
raise money for more free documentation.''
The Texinfo source for this manual may be obtained from: @*
@code{http://www.network-theory.co.uk/gcc/intro/src/}
@end titlepage
@contents
@ifnottex
@node Top
@top An Introduction to GCC
This manual provides an introduction to the GNU C and C++ Compilers,
@code{gcc} and @code{g++}, which are part of the GNU Compiler Collection
(GCC).
The development of this manual was funded entirely by
@uref{http://www.network-theory.co.uk/,Network Theory Ltd}. Copies
published by Network Theory Ltd raise money for more free documentation.
The content of this Debian packaged version adds a chapter on ``Security
enhancement options'' and makes some minor file path adjustments to match
learning experiences under the Debian environment.
@end ifnottex
@menu
* Introduction::
* Compiling a C program::
* Compilation options::
* Using the preprocessor::
* Compiling for debugging::
* Compiling with optimization::
* Compiling a C++ program::
* Security enhancement options::
* Platform-specific options::
* Troubleshooting::
* Compiler-related tools::
* How the compiler works::
* Examining compiled files::
* Common error messages::
* Getting help::
* Further reading::
* Acknowledgements::
* Other books from the publisher::
* Free software organizations::
@ifnotinfo
* GNU Free Documentation License::
@end ifnotinfo
* Index::
@end menu
@iftex
@include rms.texi
@end iftex
@node Introduction
@chapter Introduction
The purpose of this book is to explain the use of the GNU C and C++
compilers, @code{gcc} and @code{g++}. After reading this book you
should understand how to compile a program, and how to use basic
compiler options for optimization and debugging. This book does not
attempt to teach the C or C++ languages themselves, since this material
can be found in many other places (@pxref{Further reading}).
Experienced programmers who are familiar with other systems, but new to
the GNU compilers, can skip the early sections of the chapters
``@cite{Compiling a C program}'', ``@cite{Using the preprocessor}'' and
``@cite{Compiling a C++ program}''. The remaining sections and chapters
should provide a good overview of the features of GCC for those already
know how to use other compilers.
@menu
* A brief history of GCC::
* Major features of GCC::
* Programming in C and C++::
* Conventions used in this manual::
@end menu
@node A brief history of GCC
@section A brief history of GCC
@cindex @code{gcc}, GNU C Compiler
@cindex C, @code{gcc} compiler
@cindex history, of GCC
@cindex Richard Stallman, principal author of GCC
@cindex GNU Project, history of
@cindex Free Software Foundation (FSF)
The original author of the GNU C Compiler (GCC) is Richard Stallman, the
founder of the GNU Project.
The GNU Project was started in 1984 to create a complete Unix-like
operating system as free software, in order to promote freedom and
cooperation among computer users and programmers. Every Unix-like
operating system needs a C compiler, and as there were no free compilers
in existence at that time, the GNU Project had to develop one from
scratch. The work was funded by donations from individuals and
companies to the Free Software Foundation, a non-profit organization set
up to support the work of the GNU Project.
The first release of GCC was made in 1987. This was a significant
breakthrough, being the first portable ANSI C optimizing compiler
released as free software. Since that time GCC has become one of the
most important tools in the development of free software.
@cindex C++, @code{g++} compiler
@cindex @code{g++}, GNU C++ Compiler
@cindex EGCS (Experimental GNU Compiler Suite)
A major revision of the compiler came with the 2.0 series in 1992, which
added the ability to compile C++. In 1997 an experimental branch of the
compiler (EGCS) was created, to improve optimization and C++ support.
Following this work, EGCS was adopted as the new main-line of GCC
development, and these features became widely available in the 3.0
release of GCC in 2001.
@cindex Fortran, @code{g77} compiler
@cindex Objective-C
@cindex ADA, @code{gnat} compiler
@cindex Java, @code{gcj} compiler
@cindex @code{g77}, Fortran compiler
@cindex @code{gnat}, GNU ADA compiler
@cindex @code{gcj}, GNU Compiler for Java
Over time GCC has been extended to support many additional languages,
including Fortran, ADA, Java and Objective-C. The acronym GCC is now
used to refer to the ``GNU Compiler Collection''. Its development is
guided by the @dfn{GCC Steering Committee}, a group composed of
representatives from GCC user communities in industry, research and
academia.
@node Major features of GCC
@section Major features of GCC
@cindex features, of GCC
@cindex major features, of GCC
@cindex GNU Compilers, major features
This section describes some of the most important features of GCC.
First of all, GCC is a portable compiler---it runs on most platforms
available today, and can produce output for many types of processors. In
addition to the processors used in personal computers, it also supports
microcontrollers, DSPs and 64-bit CPUs.
@cindex embedded systems, cross-compilation for
GCC is not only a native compiler---it can also @dfn{cross-compile} any
program, producing executable files for a different system from the one
used by GCC itself. This allows software to be compiled for embedded
systems which are not capable of running a compiler. GCC is written in
C with a strong focus on portability, and can compile itself, so it can
be adapted to new systems easily.
GCC has multiple language @dfn{frontends}, for parsing different
languages. Programs in each language can be compiled, or
cross-compiled, for any architecture. For example, an ADA program can be
compiled for a microcontroller, or a C program for a supercomputer.
GCC has a modular design, allowing support for new languages and
architectures to be added. Adding a new language front-end to GCC
enables the use of that language on any architecture, provided that the
necessary run-time facilities (such as libraries) are available.
Similarly, adding support for a new architecture makes it available to
all languages.
Finally, and most importantly, GCC is free software, distributed under the
GNU General Public License (GNU GPL).@footnote{For details see the
license file @file{COPYING} distributed with GCC.} This means you have
the freedom to use and to modify GCC, as with all GNU software. If you
need support for a new type of CPU, a new language, or a new feature you
can add it yourself, or hire someone to enhance GCC for you. You can
hire someone to fix a bug if it is important for your work.
Furthermore, you have the freedom to share any enhancements you make to
GCC. As a result of this freedom you can also make use of enhancements
to GCC developed by others. The many features offered by GCC today show
how this freedom to cooperate works to benefit you, and everyone else
who uses GCC.
@node Programming in C and C++
@section Programming in C and C++
@cindex Lisp, compared with C/C++
@cindex Smalltalk, compared with C/C++
@cindex Scheme, compared with C/C++
@cindex Java, compared with C/C++
@cindex C/C++, risks of using
@cindex risks, examples of
C and C++ are languages that allow direct access to the computer's
memory. Historically, they have been used for writing low-level systems
software, and applications where high-performance or control over
resource usage are critical. However, great care is required to ensure
that memory is accessed correctly, to avoid corrupting other
data-structures. This book describes techniques that will help in
detecting potential errors during compilation, but the risk in using
languages like C or C++ can never be eliminated.
In addition to C and C++ the GNU Project also provides other high-level
languages, such as GNU Common Lisp (@code{gcl}), GNU Smalltalk
(@code{gst}), the GNU Scheme extension language (@code{guile}) and the
GNU Compiler for Java (@code{gcj}). These languages do not allow the
user to access memory directly, eliminating the possibility of memory
access errors. They are a safer alternative to C and C++ for many
applications.
@node Conventions used in this manual
@section Conventions used in this manual
@cindex conventions, used in manual
@cindex examples, conventions used in
@cindex shell prompt
@cindex @code{$}, shell prompt
This manual contains many examples which can be typed at the keyboard.
A command entered at the terminal is shown like this,
@example
$ @i{command}
@end example
@noindent
followed by its output. For example:
@example
$ echo "hello world"
hello world
@end example
@noindent
@cindex dollar sign @code{$}, shell prompt
The first character on the line is the terminal prompt, and should not
be typed. The dollar sign @samp{$} is used as the standard prompt in
this manual, although some systems may use a different character.
When a command in an example is too long to fit in a single line it is
wrapped and then indented on subsequent lines, like this:
@example
$ echo "an example of a line which is too long to fit
in this manual"
@end example
@noindent
When entered at the keyboard, the entire command should be typed on a
single line.
The example source files used in this manual can be downloaded from the
publisher's website,@footnote{See
@uref{http://www.network-theory.co.uk/gcc/intro/}} or entered by hand
using any text editor, such as the standard GNU editor, @code{emacs}.
The example compilation commands use @code{gcc} and @code{g++} as the
names of the GNU C and C++ compilers, and @code{cc} to refer to other
compilers. The example programs should work with any version of GCC.
Any command-line options which are only available in recent versions of
GCC are noted in the text.
@cindex shell variables
@cindex environment variables
The examples assume the use of a GNU operating system---there may be
minor differences in the output on other systems. Some non-essential and
verbose system-dependent output messages (such as very long system
paths) have been edited in the examples for brevity. The commands
for setting environment variables use the syntax of the standard GNU
shell (@code{bash}), and should work with any version of the Bourne
shell.
@node Compiling a C program
@chapter Compiling a C program
@cindex compiling C programs with @code{gcc}
This chapter describes how to compile C programs using @code{gcc}.
Programs can be compiled from a single source file or from multiple
source files, and may use system libraries and header files.
@cindex source code
@cindex machine code
@cindex executable file
@cindex binary file, also called executable file
Compilation refers to the process of converting a program from the
textual @dfn{source code}, in a programming language such as C or C++,
into @dfn{machine code}, the sequence of 1's and 0's used to control the
central processing unit (CPU) of the computer. This machine code is then
stored in a file known as an @dfn{executable file}, sometimes referred
to as a @dfn{binary file}.
@menu
* Compiling a simple C program::
* Finding errors in a simple program::
* Compiling multiple source files::
* Compiling files independently::
* Recompiling and relinking::
* A simple makefile::
* Linking with external libraries::
* Using library header files::
@end menu
@node Compiling a simple C program
@section Compiling a simple C program
@cindex Hello World program, in C
@cindex C, compiling with @code{gcc}
@cindex simple C program, compiling
The classic example program for the C language is @dfn{Hello World}.
Here is the source code for our version of the program:
@example
@verbatiminclude hello.c
@end example
@noindent
@cindex @code{.c}, C source file extension
@cindex @code{c}, C source file extension
@cindex C source file, @code{.c} extension
@cindex file extension, @code{.c} source file
@cindex extension, @code{.c} source file
We will assume that the source code is stored in a file called @file{hello.c}.
To compile the file @file{hello.c} with @code{gcc}, use the following
command:
@example
$ gcc -Wall hello.c -o hello
@end example
@noindent
@cindex @code{gcc}, simple example
@cindex @option{-o} option, set output filename
@cindex @option{o} option, set output filename
@cindex output file option, @option{-o}
@cindex @code{a.out}, default executable filename
@cindex executable, default filename @code{a.out}
@cindex default executable filename, @code{a.out}
This compiles the source code in @file{hello.c} to machine code and
stores it in an executable file @file{hello}. The output file for the
machine code is specified using the @option{-o} option. This option is
usually given as the last argument on the command line. If it is
omitted, the output is written to a default file called @file{a.out}.
Note that if a file with the same name as the executable file already
exists in the current directory it will be overwritten.
@cindex @option{-Wall} option, enable common warnings
@cindex @option{Wall} option, enable common warnings
@cindex warning options, @option{-Wall}
The option @option{-Wall} turns on all the most commonly-used compiler
warnings---@strong{it is recommended that you always use this option!}
There are many other warning options which will be discussed in later
chapters, but @option{-Wall} is the most important. GCC will not
produce any warnings unless they are enabled. Compiler warnings are an
essential aid in detecting problems when programming in C and C++.
In this case, the compiler does not produce any warnings with the
@option{-Wall} option, since the program is completely valid. Source code
which does not produce any warnings is said to @dfn{compile cleanly}.
@cindex executable, running
@cindex running an executable file, C
To run the program, type the path name of the executable like this:
@example
$ ./hello
Hello, world!
@end example
@noindent
This loads the executable file into memory and causes the CPU to begin
executing the instructions contained within it. The path @code{./}
refers to the current directory, so @code{./hello} loads and runs the
executable file @file{hello} located in the current directory.
@node Finding errors in a simple program
@section Finding errors in a simple program
@cindex @code{printf}, example of error in format
As mentioned above, compiler warnings are an essential aid when
programming in C and C++. To demonstrate this, the program below
contains a subtle error: it uses the function @code{printf} incorrectly,
by specifying a floating-point format @samp{%f} for an integer value:
@example
@verbatiminclude bad.c
@end example
@noindent
This error is not obvious at first sight, but can be detected by the
compiler if the warning option @option{-Wall} has been enabled.
Compiling the program above, @file{bad.c}, with the warning option
@option{-Wall} produces the following message:
@cindex warning, format with different type arg
@cindex format, different type arg warning
@cindex different type arg, format warning
@example
$ gcc -Wall bad.c -o bad
bad.c: In function `main':
bad.c:6: warning: double format, different
type arg (arg 2)
@end example
@noindent
This indicates that a format string has been used incorrectly in the
file @file{bad.c} at line 6. The messages produced by GCC always have
the form @i{file:line-number:message}. The compiler distinguishes
between @dfn{error messages}, which prevent successful compilation, and
@dfn{warning messages} which indicate possible problems (but do not stop
the program from compiling).
In this case, the correct format specifier should be @samp{%d}
for an integer argument. The allowed format specifiers for
@code{printf} can be found in any general book on C, such as the
@cite{GNU C Library Reference Manual} (@pxref{Further reading}).
Without the warning option @option{-Wall} the program appears to compile
cleanly, but produces incorrect results:
@cindex bug, example of
@example
$ gcc bad.c -o bad
$ ./bad
Two plus two is 2.585495 @r{(incorrect output)}
@end example
@noindent
@cindex C/C++, risks of using
@cindex risks, examples of
The incorrect format specifier causes the output to be corrupted,
because the function @code{printf} is passed an integer instead of a
floating-point number. Integers and floating-point numbers are stored
in different formats in memory, and generally occupy different numbers
of bytes, leading to a spurious result. The actual output shown above
may differ, depending on the specific platform and environment.
Clearly, it is very dangerous to develop a program without checking for
compiler warnings. If there are any functions which are not used
correctly they can cause the program to crash or produce incorrect
results. Turning on the compiler warning option @option{-Wall} will
catch many of the commonest errors which occur in C programming.
@node Compiling multiple source files
@section Compiling multiple source files
@cindex multiple files, compiling
@cindex compiling multiple files
A program can be split up into multiple files. This makes it easier to
edit and understand, especially in the case of large programs---it also
allows the individual parts to be compiled independently.
In the following example we will split up the program @dfn{Hello World}
into three files: @file{main.c}, @file{hello_fn.c} and the header file
@file{hello.h}. Here is the main program @file{main.c}:
@example
@verbatiminclude main.c
@end example
@noindent
The original call to the @code{printf} system function in the previous
program @file{hello.c} has been replaced by a call to a new external
function @code{hello}, which we will define in a separate file
@file{hello_fn.c}.
@cindex declaration, in header file
@cindex header file, declarations in
@cindex @code{.h}, header file extension
@cindex @code{h}, header file extension
@cindex header file, @code{.h} extension
@cindex file extension, @code{.h} header file
@cindex extension, @code{.h} header file
The main program also includes the header file @file{hello.h} which will
contain the declaration of the function @code{hello}. The declaration
is used to ensure that the types of the arguments and return value match
up correctly between the function call and the function definition. We
no longer need to include the system header file @file{stdio.h} in
@file{main.c} to declare the function @code{printf}, since the file
@file{main.c} does not call @code{printf} directly.
The declaration in @file{hello.h} is a single line specifying the
prototype of the function @code{hello}:
@example
@verbatiminclude hello1.h
@end example
@noindent
The definition of the function @code{hello} itself is contained in the
file @file{hello_fn.c}:
@example
@verbatiminclude hello_fn.c
@end example
@noindent
This function prints the message ``@code{Hello, }@var{name}@code{!}''
using its argument as the value of @var{name}.
@cindex @code{#include}, preprocessor directive
Incidentally, the difference between the two forms of the include
statement @code{#include "@var{FILE}.h"} and @code{#include
<@var{FILE}.h>} is that the former searches for @file{@var{FILE}.h} in
the current directory before looking in the system header file
directories. The include statement @code{#include <@var{FILE}.h>}
searches the system header files, but does not look in the current
directory by default.
To compile these source files with @code{gcc}, use the following
command:
@example
$ gcc -Wall main.c hello_fn.c -o newhello
@end example
@noindent
In this case, we use the @option{-o} option to specify a different output
file for the executable, @file{newhello}. Note that the header file
@file{hello.h} is not specified in the list of files on the command
line. The directive @code{#include "hello.h"} in the source files
instructs the compiler to include it automatically at the appropriate
points.
To run the program, type the path name of the executable:
@example
$ ./newhello
Hello, world!
@end example
@noindent
All the parts of the program have been combined into a single executable
file, which produces the same result as the executable created from the
single source file used earlier.
@node Compiling files independently
@section Compiling files independently
@cindex compiling files independently
@cindex independent compilation of files
If a program is stored in a single file then any change to an individual
function requires the whole program to be recompiled to produce a new
executable. The recompilation of large source files can be very
time-consuming.
@cindex linking, explanation of
@cindex object file, explanation of
@cindex @code{.o}, object file extension
@cindex @code{o}, object file extension
@cindex file extension, @code{.o} object file
@cindex extension, @code{.o} object file
@cindex object file, @code{.o} extension
When programs are stored in independent source files, only the files
which have changed need to be recompiled after the source code has been
modified. In this approach, the source files are compiled
separately and then @dfn{linked} together---a two stage process. In the
first stage, a file is compiled without creating an executable. The
result is referred to as an @dfn{object file}, and has the extension
@file{.o} when using GCC.
In the second stage, the object files are merged together by a separate
program called the @dfn{linker}. The linker combines all the
object files to create a single executable.
An object file contains machine code where any references to the memory
addresses of functions (or variables) in other files are left undefined.
This allows source files to be compiled without direct reference to each
other. The linker fills in these missing addresses when it produces the
executable.
@menu
* Creating object files from source files::
* Creating executables from object files::
@end menu
@node Creating object files from source files
@subsection Creating object files from source files
@cindex creating object files from source files
@cindex @option{-c} option, compile to object file
@cindex @option{c} option, compile to object file
@cindex compile to object file, @option{-c} option
@cindex object file, creating from source using option @option{-c}
The command-line option @option{-c} is used to compile a source file to
an object file. For example, the following command will compile the
source file @file{main.c} to an object file:
@example
$ gcc -Wall -c main.c
@end example
@noindent
This produces an object file @file{main.o} containing the machine code
for the @code{main} function. It contains a reference to the external
function @code{hello}, but the corresponding memory address is left
undefined in the object file at this stage (it will be filled in later
by linking).
The corresponding command for compiling the @code{hello} function in the
source file @file{hello_fn.c} is:
@example
$ gcc -Wall -c hello_fn.c
@end example
@noindent
This produces the object file @file{hello_fn.o}.
Note that there is no need to use the option @option{-o} to specify the
name of the output file in this case. When compiling with @option{-c}
the compiler automatically creates an object file whose name is the same
as the source file, but with @file{.o} instead of the original extension.
@cindex header file, not compiled
There is no need to put the header file @file{hello.h} on the command
line, since it is automatically included by the @code{#include}
statements in @file{main.c} and @file{hello_fn.c}.
@node Creating executables from object files
@subsection Creating executables from object files
@cindex creating executable files from object files
@cindex linking, creating executable files from object files
@cindex executable, creating from object files by linking
@cindex object files, linking to create executable file
The final step in creating an executable file is to use @code{gcc} to
link the object files together and fill in the missing addresses of
external functions. To link object files together, they are simply
listed on the command line:
@example
$ gcc main.o hello_fn.o -o hello
@end example
@noindent
This is one of the few occasions where there is no need to use the
@option{-Wall} warning option, since the individual source files have
already been successfully compiled to object code. Once the source
files have been compiled, linking is an unambiguous process which
either succeeds or fails (it fails only if there are references which
cannot be resolved).
@cindex linker, initial description
To perform the linking step @code{gcc} uses the linker @code{ld}, which
is a separate program. On GNU systems the GNU linker, GNU @code{ld}, is
used. Other systems may use the GNU linker with GCC, or may have their
own linkers. The linker itself will be discussed later (@pxref{How the
compiler works}). By running the linker, @code{gcc} creates an
executable file from the object files.
@c @example
@c ld main.o hello.o -o hello
@c @end example
The resulting executable file can now be run:
@example
$ ./hello
Hello, world!
@end example
@noindent
It produces the same output as the version of the program using a single
source file in the previous section.
@node Recompiling and relinking
@section Recompiling and relinking
@cindex recompiling modified source files
@cindex relinking updated object files
@cindex modified source files, recompiling
@cindex updated object files, relinking
@cindex source files, recompiling
@cindex object files, relinking
@cindex C programs, recompiling after modification
To show how source files can be compiled independently we will edit
the main program @file{main.c} and modify it to print a
greeting to @code{everyone} instead of @code{world}:
@example
@verbatiminclude main2.c
@end example
@noindent
The updated file @file{main.c} can now be recompiled with the following
command:
@example
$ gcc -Wall -c main.c
@end example
@noindent
@cindex recompiling modified source files
@cindex modified source files, recompiling
@cindex updated source files, recompiling
This produces a new object file @file{main.o}. There is no need to
create a new object file for @file{hello_fn.c}, since that file and the
related files that it depends on, such as header files, have not
changed.
@cindex relinking updated object files
@cindex linking, updated object files
The new object file can be relinked with the @code{hello} function to
create a new executable file:
@example
$ gcc main.o hello_fn.o -o hello
@end example
@noindent
The resulting executable @file{hello} now uses the new @code{main}
function to produce the following output:
@example
$ ./hello
Hello, everyone!
@end example
@noindent
Note that only the file @file{main.c} has been recompiled, and then
relinked with the existing object file for the @code{hello} function.
If the file @file{hello_fn.c} had been modified instead, we could have
recompiled @file{hello_fn.c} to create a new object file
@file{hello_fn.o} and relinked this with the existing file
@file{main.o}.@footnote{If the prototype of a function has changed, it is
necessary to modify and recompile all of the other source files which
use it.}
In a large project with many source files, recompiling only those that
have been modified can make a significant saving. The process of
recompiling only the modified files in a project can be automated with
the standard Unix program @code{make}.
@node A simple makefile
@section A simple makefile
@cindex makefile, example of
@cindex GNU Make
For those unfamiliar with @code{make}, this section provides a simple
demonstration of its use. Make is a program in its own right and can be
found on all Unix systems. To learn more about the GNU version of
@code{make} you will need to consult the @cite{GNU Make} manual by
Richard M. Stallman and Roland McGrath (@pxref{Further reading}).
@cindex target, in makefile
@cindex dependency, in makefile
@cindex command, in makefile
Make reads a description of a project from a @dfn{makefile} (by default,
called @file{Makefile} in the current directory). A makefile specifies
a set of compilation rules in terms of @dfn{targets} (such as
executables) and their @dfn{dependencies} (such as object files and
source files) in the following format:
@example
@i{target}: @i{dependencies}
@i{command}
@end example
@noindent
@cindex tab, in makefiles
@cindex separator, in makefiles
For each target, make checks the modification time of the corresponding
dependency files to determine whether the target needs to
be rebuilt using the corresponding command. Note that the
@code{@i{command}} lines in a makefile must be indented with a single
@key{TAB} character, not spaces.
@cindex implicit rules, in makefile
@cindex rules, in makefile
@cindex @code{CFLAGS}, make variable
@cindex @code{CC}, make variable
@cindex @code{CXX}, make variable
@cindex @code{CXXFLAGS}, make variable
@cindex @code{CPPFLAGS}, make variable
@cindex variables, in make
GNU Make contains many default rules, referred to as @dfn{implicit}
rules, to simplify the construction of makefiles. For example, these
specify that @file{.o} files can be obtained from @file{.c} files by
compilation, and that an executable can be made by linking together
@file{.o} files. Implicit rules are defined in terms of @dfn{make
variables}, such as @code{CC} (the C compiler) and @code{CFLAGS} (the
compilation options for C programs), which can be set using
@code{@i{VARIABLE}=@i{VALUE}} lines in the makefile. For C++ the
equivalent variables are @code{CXX} and @code{CXXFLAGS}, while the make
variable @code{CPPFLAGS} sets the preprocessor options. The implicit and
user-defined rules are automatically chained together as necessary by
GNU Make.
@need 1000
A simple @file{Makefile} for the project above can be written as
follows:
@example
@verbatiminclude c1makefile2
@end example
@noindent
The file can be read like this: using the C compiler @command{gcc},
with compilation option @option{-Wall}, build the target executable
@code{main} from the object files @file{main.o} and @file{hello_fn.o}
(these, in turn, will be built via implicit rules from @file{main.c}
and @file{hello_fn.c}). The target @code{clean} has no dependencies
and simply removes all the compiled files.@footnote{This assumes that
there is no file called @file{clean} in the current directory---see
the discussion of ``phony targets'' in the GNU Make manual for
details.} The option @option{-f} (force) on the @command{rm} command
suppresses any error messages if the files do not exist.
To use the makefile, type @command{make}. When called with no arguments,
the first target in the makefile is built, producing the executable
@file{main}:
@example
$ make
gcc -Wall -c -o main.o main.c
gcc -Wall -c -o hello_fn.o hello_fn.c
gcc main.o hello_fn.o -o main
$ ./main
Hello, world!
@end example
@noindent
To rebuild the executable after modifying a source file, simply type
@command{make} again. By checking the timestamps of the target and dependency files,
make identifies the files which have changed and regenerates the corresponding
intermediate files needed to update the targets:
@example
$ emacs main.c @r{(edit the file)}
$ make
gcc -Wall -c -o main.o main.c
gcc main.o hello_fn.o -o main
$ ./main
Hello, everyone!
@end example
@noindent
Finally, to remove the generated files, type @command{make clean}:
@example
$ make clean
rm -f main main.o hello_fn.o
@end example
@noindent
A more sophisticated makefile would usually contain additional targets
for installation (@code{make install}) and testing (@code{make check}).
The examples in the rest of this book are small enough not to need
makefiles, but the use of make is recommended for any larger programs.
@node Linking with external libraries
@section Linking with external libraries
@cindex linking, with external libraries
@cindex libraries, linking with
@cindex @code{sqrt}, example of linking with
@cindex C math library
@cindex library, C math library
@cindex math library
@cindex system libraries
@cindex external libraries, linking with
A library is a collection of precompiled object files which can be
linked into programs. The most common use of libraries is to provide
system functions, such as the square root function @code{sqrt} found in
the C math library.
@cindex libraries, stored in archive files
@cindex archive file, explanation of
@cindex @code{.a}, archive file extension
@cindex @code{a}, archive file extension
@cindex file extension, @code{.a} archive file
@cindex extension, @code{.a} archive file
@cindex archive file, @code{.a} extension
@cindex GNU archiver, @code{ar}
@cindex @code{ar}, GNU archiver
Libraries are typically stored in special @dfn{archive files} with the
extension @file{.a}, referred to as @dfn{static libraries}. They are
created from object files with a separate tool, the GNU archiver
@code{ar}, and used by the linker to resolve references to functions at
compile-time. We will see later how to create libraries using the
@command{ar} command (@pxref{Compiler-related tools}). For simplicity,
only static libraries are covered in this section---dynamic linking at
runtime using @dfn{shared libraries} will be described in the next
chapter.
@cindex system libraries, location of
@cindex C standard library
@cindex C library, standard
@cindex standard library, C
@cindex library, C standard library
The standard system libraries are usually found in the directories
@file{/usr/lib} and @file{/lib}.@footnote{On systems supporting both 64 and
32-bit executables, their libraries are stored in the directories
@file{/lib/x86_64-linux-gnu} and @file{/usr/lib/x86_64-linux-gnu}, or
@file{/lib64} and @file{/usr/lib64} for 64-bit libraries; and
@file{/lib/i386-linux-gnu} and @file{/usr/lib/i386-linux-gnu}, or @file{/lib}
and @file{/usr/lib} for 32-bit libraries, instead. @pxref{Multi-architecture
support}} For example, the C math
library is typically stored in the file @file{/usr/lib/libm.so} on Unix-like
systems. The corresponding prototype declarations for the functions in
this library are given in the header file @file{/usr/include/math.h}.
The C standard library itself is stored in @file{/usr/lib/libc.a} and
contains functions specified in the ANSI/ISO C standard, such as
@samp{printf}---this library is linked by default for every C program.
Here is an example program which makes a call to the external function
@code{sqrt} in the math library @file{libm.a}:
@example
@verbatiminclude calc.c
@end example
@noindent
Trying to create an executable from this source file alone causes
the compiler to give an error at the link stage:
@cindex undefined reference error
@cindex reference, undefined due to missing library
@cindex libraries, link error due to undefined reference
@example
@group
$ gcc -Wall calc.c -o calc
/tmp/ccbR6Ojm.o: In function `main':
/tmp/ccbR6Ojm.o(.text+0x19): undefined reference
to `sqrt'
@end group
@end example
@noindent
The problem is that the reference to the @code{sqrt} function cannot be
resolved without the external math library @file{libm.a}. The function
@code{sqrt} is not defined in the program or the default library
@file{libc.a}, and the compiler does not link to the file @file{libm.a}
unless it is explicitly selected.
@cindex @file{/tmp} directory, temporary files
@cindex temporary files, written to @file{/tmp}
@cindex object files, temporary
Incidentally, the file mentioned in the error message
@file{/tmp/ccbR60jm.o} is a temporary object file created by the
compiler from @file{calc.c}, in order to carry out the linking process.
To enable the compiler to link the @code{sqrt} function to the main
program @file{calc.c} we need to supply the library @file{libm.a}. One
obvious but cumbersome way to do this is to specify it explicitly on the
command line:
@example
$ gcc -Wall calc.c /usr/lib/libm.a -o calc
@end example
@noindent
The library @file{libm.a} contains object files for all the mathematical
functions, such as @code{sin}, @code{cos}, @code{exp}, @code{log} and
@code{sqrt}. The linker searches through these to find the object
file containing the @code{sqrt} function.
Once the object file for the @code{sqrt} function has been found, the
main program can be linked and a complete executable produced:
@example
$ ./calc
The square root of 2.0 is 1.414214
@end example
@noindent
The executable file includes the machine code for the main function and
the machine code for the @code{sqrt} function, copied from the corresponding
object file in the library @file{libm.a}.
@cindex linking, with library using @option{-l}
@cindex libraries, linking with
@cindex @option{-l} option, linking with libraries
@cindex @option{-lm} option, link with math library
@cindex @option{l} option, linking with libraries
@cindex math library, linking with @option{-lm}
To avoid the need to specify long paths on the command line, the
compiler provides a short-cut option @samp{-l} for linking against
libraries. For example, the following command,
@example
$ gcc -Wall calc.c -lm -o calc
@end example
@noindent
is equivalent to the original command above using the full library name
@file{/usr/lib/libm.a}.
In general, the compiler option @option{-l@var{NAME}} will attempt to
link object files with a library file @file{lib@var{NAME}.a} in the
standard library directories. Additional directories can specified with
command-line options and environment variables, to be discussed shortly.
A large program will typically use many @option{-l} options to link
libraries such as the math library, graphics libraries and networking
libraries.
@menu
* Link order of libraries::
@end menu
@node Link order of libraries
@subsection Link order of libraries
@cindex libraries, link order
@cindex link order, of libraries
@cindex link order, from left to right
The traditional behavior of linkers is to search for
external functions from left to right in the libraries specified on the
command line. This means that a library containing the definition of a
function should appear after any source files or object files which use
it. This includes libraries specified with the short-cut @option{-l}
option, as shown in the following command:
@example
$ gcc -Wall calc.c -lm -o calc @r{(correct order)}
@end example
@noindent
With some linkers the opposite ordering (placing the @option{-lm}
option before the file which uses it) would result in an error,
@example
$ cc -Wall -lm calc.c -o calc @r{(incorrect order)}
main.o: In function `main':
main.o(.text+0xf): undefined reference to `sqrt'
@end example
@noindent
@cindex undefined reference error
@cindex error, undefined reference due to library link order
@cindex linking, undefined reference error due to library link order
because there is no library or object file containing @code{sqrt} after
@file{calc.c}. The option @option{-lm} should appear after the file
@file{calc.c}.
When several libraries are being used, the same convention should be
followed for the libraries themselves. A library which calls an
external function defined in another library should appear before the
library containing the function.
@cindex ordering of libraries
@cindex libraries, link order
For example, a program @file{data.c} using the GNU Linear Programming
library @file{libglpk.a}, which in turn uses the math library
@file{libm.a}, should be compiled as,
@example
$ gcc -Wall data.c -lglpk -lm
@end example
@noindent
since the object files in @file{libglpk.a} use functions defined in
@file{libm.a}.
@c With some compilers the opposite ordering would result in
@c an error,
@c
@c @example
@c $ cc -Wall data.c -lm -lglpk @r{(incorrect order)}
@c main.o: In function `main':
@c main.o(.text+0xf): undefined reference to `exp'
@c @end example
@c @noindent
@c because there is no library containing mathematical functions used by
@c @file{libglpk.a} (such as @code{exp}) after the @option{-lglpk} option.
Most current linkers will search all libraries, regardless
of order, but since some do not do this it is best to follow the
convention of ordering libraries from left to right.
This is worth keeping in mind if you ever encounter unexpected problems
with undefined references, and all the necessary libraries appear to be
present on the command line.
@node Using library header files
@section Using library header files
@cindex header file, missing
@cindex declaration, missing
@cindex missing header files
@cindex library header files, using
When using a library it is essential to include the appropriate header
files, in order to declare the function arguments and return values with
the correct types. Without declarations, the arguments of a function can
be passed with the wrong type, causing corrupted results.
The following example shows another program which makes a function call
to the C math library. In this case, the function @code{pow} is used to
compute the cube of two (2 raised to the power of 3):
@example
@verbatiminclude badpow.c
@end example
@noindent
However, the program contains an error---the @code{#include} statement
for @file{math.h} is missing, so the prototype @code{double pow (double
x, double y)} given there will not be seen by the compiler.
@c Note that in this case the format specifier
@c @code{%f} is correct, since @code{x} is a floating point variable.
@c @cindex @code{math.h}, header file for mathematical functions
Compiling the program without any warning options will produce an
executable file which gives incorrect results:
@cindex bug, example of
@example
$ gcc badpow.c -lm
$ ./a.out
Two cubed is 2.851120 @r{(incorrect result, should be 8)}
@end example
@noindent
@cindex C/C++, risks of using
The results are corrupted because the arguments and return value of the
call to @code{pow} are passed with incorrect types.@footnote{The actual
output shown above may differ, depending on the specific platform and
environment.} This can be detected by turning on the warning option
@option{-Wall}:
@example
$ gcc -Wall badpow.c -lm
badpow.c: In function `main':
badpow.c:6: warning: implicit declaration of
function `pow'
@end example
@noindent
@cindex implicit declaration of function
@cindex header file, missing header causes implicit declaration
@cindex missing header file, causes implicit declaration
@c The error is now detected and can be fixed by adding the line
@c @code{#include <math.h>} to the beginning of the source file.
This example shows again the importance of using the warning option
@option{-Wall} to detect serious problems that could otherwise easily be
overlooked.
@node Compilation options
@chapter Compilation options
@cindex compilation, options
@cindex options, compilation
This chapter describes other commonly-used compiler options available in
GCC. These options control features such as the search paths used for
locating libraries and include files, the use of additional warnings and
diagnostics, preprocessor macros and C language dialects.
@menu
* Setting search paths::
* Shared libraries and static libraries::
* C language standards::
* Warning options in -Wall::
* Additional warning options::
* Recommended warning options::
@end menu
@node Setting search paths
@section Setting search paths
@cindex search paths
@cindex paths, search
In the last chapter, we saw how to link to a program with functions in
the C math library @file{libm.a}, using the short-cut option @option{-lm}
and the header file @file{math.h}.
A common problem when compiling a program using library header files is
the error:
@cindex No such file or directory, header file not found
@cindex header file, not found
@example
@var{FILE.h}: No such file or directory
@end example
@noindent
This occurs if a header file is not present in the standard include file
directories used by @code{gcc}. A similar problem can occur for
libraries:
@cindex cannot find @var{library} error
@cindex linkr error, cannot find library
@example
/usr/bin/ld: cannot find @var{library}
@end example
@noindent
This happens if a library used for linking is not present in the
standard library directories used by @code{gcc}.
By default, @code{gcc} searches the following directories for header
files:
@cindex ld: cannot find library error
@cindex link error, cannot find library
@cindex default directories, linking and header files
@cindex linking, default directories
@cindex header file, default directories
@example
/usr/local/include/
/usr/include/
@end example
@noindent
and the following directories for libraries:
@example
/usr/local/lib/
/usr/lib/
@end example
@noindent
The list of directories for header files is often referred to as the
@dfn{include path}, and the list of directories for libraries as the
@dfn{library search path} or @dfn{link path}.
@cindex libraries, on 64-bit platforms
@cindex 64-bit platforms, additional library directories
@cindex system libraries, location of
The directories on these paths are searched in order, from first to last in
the two lists above.@footnote{The default search paths may also include
additional system-dependent or site-specific directories, and directories in
the GCC installation itself. For example, on 64-bit platforms additional
@file{/usr/lib/x86_64-linux-gnu} or @file{/usr/lib64} directories may also be
searched by default. @pxref{Multi-architecture support}}
For example, a header file found in
@file{/usr/local/include} takes precedence over a file with the same
name in @file{/usr/include}. Similarly, a library found in
@file{/usr/local/lib} takes precedence over a library with the same
name in @file{/usr/lib}.
@cindex @option{-L} option, library search path
@cindex @option{L} option, library search path
@cindex @option{-I} option, include path
@cindex @option{I} option, include path
@cindex libraries, extending search path with @option{-L}
@cindex include path, extending with @option{-I}
@cindex header file, include path---extending with @option{-I}
When additional libraries are installed in other directories it is
necessary to extend the search paths, in order for the libraries to be
found. The compiler options @option{-I} and @option{-L} add new
directories to the beginning of the include path and library search path
respectively.
@menu
* Search path example::
* Environment variables::
* Extended search paths::
@end menu
@node Search path example
@subsection Search path example
@cindex search paths, example
@cindex @code{gdbm}, GNU DBM library
@cindex key-value pairs, stored with GDBM
@cindex DBM file, created with @code{gdbm}
The following example program uses a library that might be installed as
an additional package on a system---the GNU Database Management Library
(GDBM). The GDBM Library stores key-value pairs in a DBM file, a type
of data file which allows values to be stored and indexed by a @dfn{key}
(an arbitrary sequence of characters). Here is the example program
@file{dbmain.c}, which creates a DBM file containing a key
@samp{testkey} with the value @samp{testvalue}:
@example
@verbatiminclude dbmain.c
@end example
@noindent
The program uses the header file @file{gdbm.h} and the library
@file{libgdbm.a}. If the library has been installed in the default
location of @file{/usr/local/lib}, with the header file in
@file{/usr/local/include}, then the program can be compiled with the
following simple command:
@example
$ gcc -Wall dbmain.c -lgdbm
@end example
@noindent
Both these directories are part of the default @code{gcc} include and
link paths.
However, if GDBM has been installed in a different location, trying to
compile the program will give the following error:
@cindex No such file or directory, header file not found
@example
$ gcc -Wall dbmain.c -lgdbm
dbmain.c:1: gdbm.h: No such file or directory
@end example
@noindent
For example, if version 1.8.3 of the GDBM package is installed under the
directory @file{/opt/gdbm-1.8.3} the location of the header file would be,
@example
/opt/gdbm-1.8.3/include/gdbm.h
@end example
@noindent
which is not part of the default @code{gcc} include path. Adding the
appropriate directory to the include path with the command-line option
@option{-I} allows the program to be compiled, but not linked:
@cindex cannot find @var{library} error
@example
$ gcc -Wall -I/opt/gdbm-1.8.3/include dbmain.c -lgdbm
/usr/bin/ld: cannot find -lgdbm
collect2: ld returned 1 exit status
@end example
@noindent
The directory containing the library is still missing from the link
path.
@c The location of the library itself would be,
@c @example
@c /opt/gdbm-1.8.3/lib/libgdbm.a
@c @end example
@c @noindent
It can be added to the link path using the following option:
@example
-L/opt/gdbm-1.8.3/lib/
@end example
@noindent
The following command line allows the program to be compiled and
linked:
@example
$ gcc -Wall -I/opt/gdbm-1.8.3/include
-L/opt/gdbm-1.8.3/lib dbmain.c -lgdbm
@end example
@noindent
This produces the final executable linked to the GDBM library. Before
seeing how to run this executable we will take a brief look at the
environment variables that affect the @option{-I} and @option{-L} options.
Note that you should never place the absolute paths of header files in
@code{#include} statements in your source code, as this will prevent the
program from compiling on other systems. The @option{-I} option or the
@env{INCLUDE_PATH} variable described below should always be used to set
the include path for header files.
@node Environment variables
@subsection Environment variables
@cindex environment variables, for default search paths
@cindex shell variables
The search paths for header files and libraries can also be controlled
through environment variables in the shell. These may be set
automatically for each session using the appropriate login file, such as
@file{.bash_profile} in the case of GNU Bash.
@cindex @code{bash} profile file, login settings
@cindex include path, setting with environment variables
@cindex C include path
@cindex C++ include path
@cindex @env{C_INCLUDE_PATH}
@cindex @env{CPLUS_INCLUDE_PATH}
Additional directories can be added to the include path using the
environment variable @env{C_INCLUDE_PATH} (for C header files) or
@env{CPLUS_INCLUDE_PATH} (for C++ header files). For example, the
following commands will add @file{/opt/gdbm-1.8.3/include} to the
include path when compiling C programs:
@example
$ C_INCLUDE_PATH=/opt/gdbm-1.8.3/include
$ export C_INCLUDE_PATH
@end example
@noindent
and similarly for C++ programs:
@example
$ CPLUS_INCLUDE_PATH=/opt/gdbm-1.8.3/include
$ export CPLUS_INCLUDE_PATH
@end example
@noindent
This directory will be searched after any
directories specified on the command line with the option @option{-I},
and before the standard default directories (such as @file{/usr/local/include}
and @file{/usr/include}). The shell command @code{export} is needed to
make the environment variable available to programs outside the shell
itself, such as the compiler---it is only needed once for each variable
in each shell session, and can also be set in the appropriate login
file.@footnote{In GNU Bash, the shorter form @code{export @var{VARIABLE}=@var{VALUE}}
is also allowed.}
Similarly, additional directories can be added to the link path using
the environment variable @env{LIBRARY_PATH}. For example, the following
commands will add @file{/opt/gdbm-1.8.3/lib} to the link path:
@cindex link path, setting with environment variable
@example
$ LIBRARY_PATH=/opt/gdbm-1.8.3/lib
$ export LIBRARY_PATH
@end example
@noindent
This directory will be searched after any directories specified on the
command line with the option @option{-L}, and before the standard
default directories (such as @file{/usr/local/lib} and @file{/usr/lib}).
With the environment variable settings given above the program
@file{dbmain.c} can be compiled without the @option{-I} and @option{-L}
options,
@example
$ gcc -Wall dbmain.c -lgdbm
@end example
@noindent
because the default paths now use the directories specified in the
environment variables @env{C_INCLUDE_PATH} and @env{LIBRARY_PATH}. The
same compilation command with @code{g++} would use the environment
variables @env{CPLUS_INCLUDE_PATH} and @env{LIBRARY_PATH}.
@c Note
@c that these defaults are in addition to the system directories
@c @file{/usr/include}, @file{/usr/lib}, @file{/usr/local/include} and
@c @file{/usr/local/lib} which are always searched.
@node Extended search paths
@subsection Extended search paths
@cindex multiple directories, on include and link paths
@cindex extended search paths, for include and link directories
@cindex search paths, extended
Following the standard Unix convention for search paths, several
directories can be specified together in an environment variable
as a colon separated list:
@example
@var{DIR1}:@var{DIR2}:@var{DIR3}:...
@end example
@noindent
The directories are then searched in order from left to right. A single
dot @samp{.} can be used to specify the current directory.@footnote{The
current directory can also be specified using an empty path element. For
example, @code{:@var{DIR1}:@var{DIR2}} is equivalent to
@code{.:@var{DIR1}:@var{DIR2}}.}
For example, the following settings create default include and link
paths for packages installed in the current directory @file{.} and the
@file{include} and @file{lib} directories under @file{/opt/gdbm-1.8.3}
and @file{/net} respectively:
@example
$ C_INCLUDE_PATH=.:/opt/gdbm-1.8.3/include:/net/include
$ LIBRARY_PATH=.:/opt/gdbm-1.8.3/lib:/net/lib
@end example
@noindent
For C++ programs, use the environment variable @env{CPLUS_INCLUDE_PATH}
instead of @env{C_INCLUDE_PATH}.
To specify multiple search path directories on the command line, the
options @option{-I} and @option{-L} can be repeated. For example, the
following command,
@example
$ gcc -I. -I/opt/gdbm-1.8.3/include -I/net/include
-L. -L/opt/gdbm-1.8.3/lib -L/net/lib .....
@end example
@noindent
is equivalent to the environment variable settings given above.
When environment variables and command-line options are used together
the compiler searches the directories in the following order:
@enumerate
@item command-line options @option{-I} and @option{-L}, from left to right
@item directories specified by environment variables, such as @env{C_INCLUDE_PATH} (for C programs), @env{CPLUS_INCLUDE_PATH} (for C++ programs) and @env{LIBRARY_PATH}
@item default system directories
@end enumerate
@noindent
In day-to-day usage, directories are usually added to the search paths
with the options @option{-I} and @option{-L}.
@node Shared libraries and static libraries
@section Shared libraries and static libraries
@cindex shared libraries
@cindex static libraries
Although the example program above has been successfully compiled and
linked, a final step is needed before being able to load and run the
executable file.
If an attempt is made to start the executable directly, the following
error will occur on most systems:
@cindex error while loading shared libraries
@cindex cannot open shared object file
@cindex shared libraries, error while loading
@cindex libraries, error while loading shared library
@example
$ ./a.out
./a.out: error while loading shared libraries:
libgdbm.so.3: cannot open shared object file:
No such file or directory
@end example
@noindent
This is because the GDBM package provides a @dfn{shared library}. This
type of library requires special treatment---it must be loaded from
disk before the executable will run.
External libraries are usually provided in two forms: @dfn{static
libraries} and @dfn{shared libraries}. Static libraries are the
@file{.a} files seen earlier. When a program is linked against a static
library, the machine code from the object files for any external
functions used by the program is copied from the library into the final
executable.
@cindex @code{.so}, shared object file extension
@cindex @code{so}, shared object file extension
@cindex extension, @code{.so} shared object file
@cindex file extension, @code{.so} shared object file
@cindex shared object file, @code{.so} extension
@cindex dynamically linked library, see shared libraries
@cindex DLL (dynamically linked library), see shared libraries
Shared libraries are handled with a more advanced form of linking, which
makes the executable file smaller. They use the extension @file{.so},
which stands for @dfn{shared object}.
@cindex loader function
@cindex dynamic loader
@cindex linking, dynamic (shared libraries)
An executable file linked against a shared library contains only a small
table of the functions it requires, instead of the complete machine code
from the object files for the external functions. Before the executable
file starts running, the machine code for the external functions is
copied into memory from the shared library file on disk by the operating
system---a process referred to as @dfn{dynamic linking}.
@cindex shared libraries, advantages of
@cindex disk space, reduced usage by shared libraries
Dynamic linking makes executable files smaller and saves disk space,
because one copy of a library can be shared between multiple programs.
Most operating systems also provide a virtual memory mechanism which
allows one copy of a shared library in physical memory to be used by all
running programs, saving memory as well as disk space.
Furthermore, shared libraries make it possible to update a library
without recompiling the programs which use it (provided the interface to
the library does not change).
Because of these advantages @code{gcc} compiles programs to use shared
libraries by default on most systems, if they are available. Whenever a
static library @file{lib@var{NAME}.a} would be used for linking with the
option @option{-l@var{NAME}} the compiler first checks for an
alternative shared library with the same name and a @file{.so} extension.
In this case, when the compiler searches for the @file{libgdbm}
library in the link path, it finds the following two files in
the directory @file{/opt/gdbm-1.8.3/lib}:
@example
$ cd /opt/gdbm-1.8.3/lib
$ ls libgdbm.*
libgdbm.a libgdbm.so
@end example
@noindent
Consequently, the @file{libgdbm.so} shared object file is used in
preference to the @file{libgdbm.a} static library.
@cindex @option{-rpath} option, set run-time shared library search path
@cindex @option{rpath} option, set run-time shared library search path
However, when the executable file is started its loader function must
find the shared library in order to load it into memory. By default the
loader searches for shared libraries only in a predefined set of system
directories, such as @file{/usr/local/lib} and @file{/usr/lib}. If the
library is not located in one of these directories it must be added to
the load path.@footnote{Note that the directory containing the shared
library can, in principle, be stored (``hard-coded'') in the executable
itself using the linker option @option{-rpath}, but this is not usually
done since it creates problems if the library is moved or the executable
is copied to another system.}
@cindex @env{LD_LIBRARY_PATH}, shared library load path
@cindex shared libraries, setting load path
@cindex environment variables
@cindex shell variables
The simplest way to set the load path is through the environment
variable @env{LD_LIBRARY_PATH}. For example, the following commands
set the load path to @file{/opt/gdbm-1.8.3/lib} so that
@file{libgdbm.so} can be found:
@example
$ LD_LIBRARY_PATH=/opt/gdbm-1.8.3/lib
$ export LD_LIBRARY_PATH
$ ./a.out
Storing key-value pair... done.
@end example
@noindent
The executable now runs successfully, prints its message and creates a
DBM file called @file{test} containing the key-value pair
@samp{testkey} and @samp{testvalue}.
@cindex environment variables, setting permanently
@cindex shell variables, setting permanently
@cindex login file, setting environment variables in
@cindex profile file, setting environment variables in
To save typing, the @env{LD_LIBRARY_PATH} environment variable can be
set automatically for each session using the appropriate login file, such as
@file{.bash_profile} for the GNU Bash shell.
@cindex @code{bash} profile file, login settings
Several shared library directories can be placed in the load path, as a
colon separated list
@code{@var{DIR1}:@var{DIR2}:@var{DIR3}:...:@var{DIRN}}. For example,
the following command sets the load path to use the @file{lib}
directories under @file{/opt/gdbm-1.8.3} and @file{/opt/gtk-1.4}:
@cindex environment variables, extending an existing path
@cindex paths, extending environment variable
@example
$ LD_LIBRARY_PATH=/opt/gdbm-1.8.3/lib:/opt/gtk-1.4/lib
$ export LD_LIBRARY_PATH
@end example
@noindent
If the load path contains existing entries, it can be extended using the
syntax @code{LD_LIBRARY_PATH=@var{NEWDIRS}:$LD_LIBRARY_PATH}. For
example, the following command adds the directory
@file{/opt/gsl-1.5/lib} to the load path shown above:
@example
$ LD_LIBRARY_PATH=/opt/gsl-1.5/lib:$LD_LIBRARY_PATH
$ echo $LD_LIBRARY_PATH
/opt/gsl-1.5/lib:/opt/gdbm-1.8.3/lib:/opt/gtk-1.4/lib
@end example
@noindent
It is possible for the system administrator to set the
@env{LD_LIBRARY_PATH} variable for all users, by adding it to a default
login script, such as @file{/etc/profile}. On GNU systems, a
system-wide path can also be defined in the loader configuration file
@file{/etc/ld.so.conf}.
@cindex loader configuration file, @code{ld.so.conf}
@cindex @code{ld.so.conf}, loader configuration file
@cindex @option{-static} option, force static linking
@cindex @option{static} option, force static linking
@cindex static linking, forcing with @option{-static}
Alternatively, static linking can be forced with the @option{-static}
option to @code{gcc} to avoid the use of shared libraries:
@example
$ gcc -Wall -static -I/opt/gdbm-1.8.3/include/
-L/opt/gdbm-1.8.3/lib/ dbmain.c -lgdbm
@end example
@noindent
This creates an executable linked with the static library
@file{libgdbm.a} which can be run without setting the environment
variable @env{LD_LIBRARY_PATH} or putting shared libraries in
the default directories:
@example
$ ./a.out
Storing key-value pair... done.
@end example
@noindent
As noted earlier, it is also possible to link directly with
individual library files by specifying the full path to the library
on the command line. For example, the following command will link
directly with the static library @file{libgdbm.a},
@example
$ gcc -Wall -I/opt/gdbm-1.8.3/include
dbmain.c /opt/gdbm-1.8.3/lib/libgdbm.a
@end example
@noindent
and the command below will link with the shared library file
@file{libgdbm.so}:
@example
$ gcc -Wall -I/opt/gdbm-1.8.3/include
dbmain.c /opt/gdbm-1.8.3/lib/libgdbm.so
@end example
@noindent
In the latter case it is still necessary to set the library load
path when running the executable.
@node C language standards
@section C language standards
@cindex C language, dialects of
@cindex dialects of C language
@cindex ANSI/ISO C, compared with GNU C extensions
@cindex ISO C, compared with GNU C extensions
@cindex GNU C extensions, compared with ANSI/ISO C
@cindex @option{-ansi} option, disable language extensions
@cindex @option{ansi} option, disable language extensions
@cindex @option{-pedantic} option, conform to the ANSI standard (with @option{-ansi})
@cindex @option{pedantic} option
@cindex @option{-std} option, select specific language standard
@cindex @option{std} option, select specific language standard
By default, @code{gcc} compiles programs using the GNU dialect of the C
language, referred to as @dfn{GNU C}. This dialect incorporates the
official ANSI/ISO standard for the C language with several useful GNU
extensions, such as nested functions and variable-size arrays. Most
ANSI/ISO programs will compile under GNU C without changes.
There are several options which control the dialect of C used by
@code{gcc}. The most commonly-used options are @option{-ansi} and
@option{-pedantic}. The specific dialects of the C language for each
standard can also be selected with the @option{-std} option.
@menu
* ANSI/ISO::
* Strict ANSI/ISO::
* Selecting specific standards::
@end menu
@node ANSI/ISO
@subsection ANSI/ISO
@cindex ANSI/ISO C, controlled with @option{-ansi} option
@cindex ISO C, controlled with @option{-ansi} option
Occasionally a valid ANSI/ISO program may be incompatible with the
extensions in GNU C. To deal with this situation, the compiler option
@option{-ansi} disables those GNU extensions which are in conflict with the
ANSI/ISO standard. On systems using the GNU C Library (@code{glibc}) it
also disables extensions to the C standard library. This allows
programs written for ANSI/ISO C to be compiled without any unwanted
effects from GNU extensions.
For example, here is a valid ANSI/ISO C program which uses a variable
called @code{asm}:
@example
@verbatiminclude ansi.c
@end example
@noindent
The variable name @code{asm} is valid under the ANSI/ISO standard, but
this program will not compile in GNU C because @code{asm} is a GNU C
keyword extension (it allows native assembly instructions to be used in
C functions). Consequently, it cannot be used as a variable name
without giving a compilation error:
@cindex keywords, additional in GNU C
@cindex parse error due to language extensions
@example
$ gcc -Wall ansi.c
ansi.c: In function `main':
ansi.c:6: parse error before `asm'
ansi.c:7: parse error before `asm'
@end example
@noindent
In contrast, using the @option{-ansi} option disables the @code{asm}
keyword extension, and allows the program above to be compiled
correctly:
@example
$ gcc -Wall -ansi ansi.c
$ ./a.out
the string asm is '6502'
@end example
@noindent
For reference, the non-standard keywords and macros defined by the GNU C
extensions are @code{asm}, @code{inline}, @code{typeof}, @code{unix} and
@code{vax}. More details can be found in the GCC Reference Manual
``@cite{Using GCC}'' (@pxref{Further reading}).
@cindex @code{asm} extension keyword
@cindex @code{typeof}, GNU C extension keyword
@cindex @code{unix}, GNU C extension keyword
@cindex @code{vax}, GNU C extension keyword
The next example shows the effect of the @option{-ansi} option on
systems using the GNU C Library, such as GNU/Linux systems. The program
below prints the value of pi, @math{\pi=3.14159...}, from the
preprocessor definition @code{M_PI} in the header file @file{math.h}:
@example
@verbatiminclude pi.c
@end example
@noindent
The constant @code{M_PI} is not part of the ANSI/ISO C standard library
(it comes from the BSD version of Unix). In this case, the program will
not compile with the @option{-ansi} option:
@cindex undeclared identifier error for C library, when using @option{-ansi} option
@example
$ gcc -Wall -ansi pi.c
pi.c: In function `main':
pi.c:7: `M_PI' undeclared (first use in this function)
pi.c:7: (Each undeclared identifier is reported only once
pi.c:7: for each function it appears in.)
@end example
@noindent
The program can be compiled without the @option{-ansi} option. In this
case both the language and library extensions are enabled by default:
@example
$ gcc -Wall pi.c
$ ./a.out
the value of pi is 3.141593
@end example
@noindent
It is also possible to compile the program using ANSI/ISO C, by enabling
only the extensions in the GNU C Library itself. This can be achieved
by defining special macros, such as @code{_GNU_SOURCE}, which enable
extensions in the GNU C Library:@footnote{The @option{-D} option for
defining macros will be explained in detail in the next chapter.}
@cindex @code{_GNU_SOURCE} macro, enables extensions to GNU C Library
@cindex @code{GNU_SOURCE} macro (@code{_GNU_SOURCE}), enables extensions to GNU C Library
@example
$ gcc -Wall -ansi -D_GNU_SOURCE pi.c
$ ./a.out
the value of pi is 3.141593
@end example
@noindent
@cindex feature test macros, GNU C Library
@cindex GNU C Library, feature test macros
@cindex POSIX extensions, GNU C Library
@cindex BSD extensions, GNU C Library
@cindex XOPEN extensions, GNU C Library
@cindex SVID extensions, GNU C Library
The GNU C Library provides a number of these macros (referred to as
@dfn{feature test macros}) which allow control over the support for
POSIX extensions (@w{@code{_POSIX_C_SOURCE}}), BSD extensions
(@w{@code{_BSD_SOURCE}}), SVID extensions (@w{@code{_SVID_SOURCE}}),
XOPEN extensions (@w{@code{_XOPEN_SOURCE}}) and GNU extensions
(@w{@code{_GNU_SOURCE}}).
The @w{@code{_GNU_SOURCE}} macro enables all the extensions together,
with the POSIX extensions taking precedence over the others in cases
where they conflict. Further information about feature test macros can
be found in the @cite{GNU C Library Reference Manual} (@pxref{Further
reading}).
@node Strict ANSI/ISO
@subsection Strict ANSI/ISO
@cindex @option{pedantic} option
@cindex ANSI/ISO C, pedantic diagnostics option
@cindex strict ANSI/ISO C, @option{-pedantic} option
The command-line option @option{-pedantic} in combination with @option{-ansi}
will cause @code{gcc} to reject all GNU C extensions, not just those
that are incompatible with the ANSI/ISO standard. This helps you to write
portable programs which follow the ANSI/ISO standard.
Here is a program which uses variable-size arrays, a GNU C extension.
The array @code{x[n]} is declared with a length specified by the integer
variable @code{n}.
@cindex variable-size arrays
@cindex arrays, variable-size
@example
@verbatiminclude gnuarray.c
@end example
@noindent
This program will compile with @option{-ansi}, because support for variable
length arrays does not interfere with the compilation of valid
ANSI/ISO programs---it is a backwards-compatible extension:
@example
$ gcc -Wall -ansi gnuarray.c
@end example
@noindent
However, compiling with @option{-ansi -pedantic} reports warnings about
violations of the ANSI/ISO standard:
@example
$ gcc -Wall -ansi -pedantic gnuarray.c
gnuarray.c: In function `main':
gnuarray.c:5: warning: ISO C90 forbids variable-size
array `x'
@end example
@noindent
Note that an absence of warnings from @option{-ansi -pedantic} does not
guarantee that a program strictly conforms to the ANSI/ISO standard. The
standard itself specifies only a limited set of circumstances that
should generate diagnostics, and these are what @option{-ansi -pedantic}
reports.
@node Selecting specific standards
@subsection Selecting specific standards
@cindex @option{-std} option, select specific language standard
@cindex @option{std} option, select specific language standard
@cindex @code{c89}/@code{c99}, selected with @option{-std}
@cindex @code{gnu89}/@code{gnu99}, selected with @option{-std}
@cindex @code{iso9899:1990}/@code{iso9899:1999}, selected with @option{-std}
@cindex selecting specific language standards, with @option{-std}
@cindex language standards, selecting with @option{-std}
The specific language standard used by GCC can be controlled with the
@option{-std} option. The following C language standards are supported:
@table @asis
@item @option{-std=c89} or @option{-std=iso9899:1990}
The original ANSI/ISO C language standard (ANSI X3.159-1989, ISO/IEC
9899:1990). GCC incorporates the corrections in the two ISO Technical
Corrigenda to the original standard.
@item @option{-std=iso9899:199409}
The ISO C language standard with ISO Amendment 1, published in 1994.
This amendment was mainly concerned with internationalization, such as
adding support for multibyte characters to the C library.
@item @option{-std=c99} or @option{-std=iso9899:1999}
The revised ISO C language standard, published in 1999 (ISO/IEC 9899:1999).
@end table
@noindent
The C language standards with GNU extensions can be selected with the
options @option{-std=gnu89} and @option{-std=gnu99}.
@node Warning options in -Wall
@section Warning options in @code{-Wall}
@cindex warning options, in detail
As described earlier (@pxref{Compiling a simple C program}), the warning
option @option{-Wall} enables warnings for many common errors, and
should always be used. It combines a large
number of other, more specific, warning options which can also be
selected individually. Here is a summary of these options:
@table @asis
@item @option{-Wcomment} @r{(included in @option{-Wall})}
@cindex comments, nested
@cindex nested comments, warning of
@cindex @option{-Wcomment} option, warn about nested comments
@cindex @option{Wcomment} option, warn about nested comments
@cindex @option{comment} warning option, warn about nested comments
This option warns about nested comments. Nested comments typically
arise when a section of code containing comments is later @dfn{commented
out}:
@example
/* commented out
double x = 1.23 ; /* x-position */
*/
@end example
@noindent
Nested comments can be a source of confusion---the safe way to ``comment
out'' a section of code containing comments is to surround it with the
preprocessor directive @code{#if 0 ... #endif}:
@cindex @code{#if}, preprocessor directive
@example
/* commented out */
#if 0
double x = 1.23 ; /* x-position */
#endif
@end example
@item @option{-Wformat} @r{(included in @option{-Wall})}
@cindex @option{-Wformat} option, warn about incorrect format strings
@cindex format strings, incorrect usage warning
@cindex @code{printf}, incorrect usage warning
@cindex @code{scanf}, incorrect usage warning
This option warns about the incorrect use of format strings in functions
such as @code{printf} and @code{scanf}, where the format specifier does
not agree with the type of the corresponding function argument.
@item @option{-Wunused} @r{(included in @option{-Wall})}
@cindex unused variable warning
@cindex @option{-Wunused} option, unused variable warning
@cindex @option{Wunused} option, unused variable warning
This option warns about unused variables. When a variable is declared
but not used this can be the result of another variable being
accidentally substituted in its place. If the variable is genuinely not
needed it can be removed from the source code.
@item @option{-Wimplicit} @r{(included in @option{-Wall})}
@cindex @option{-Wimplicit} option, warn about missing declarations
@cindex @option{Wimplicit} option, warn about missing declarations
@cindex implicit declaration of function
@cindex missing prototypes warning
@cindex prototypes, missing
This option warns about any functions that are used without being
declared. The most common reason for a function to be used without
being declared is forgetting to include a header file.
@item @option{-Wreturn-type} @r{(included in @option{-Wall})}
@cindex return type, invalid
@cindex empty @code{return}, incorrect use of
@cindex void @code{return}, incorrect use of
@cindex @option{-Wreturn-type} option, warn about incorrect return types
@cindex @option{Wreturn-type} option, warn about incorrect return types
This option warns about functions that are defined without a return type
but not declared @code{void}. It also catches empty @code{return}
statements in functions that are not declared @code{void}.
For example, the following program does not use an explicit return
value:
@example
@verbatiminclude main4.c
@end example
@noindent
The lack of a return value in the code above could be the result of an
accidental omission by the programmer---the value returned by the main
function is actually the return value of the @code{printf} function (the
number of characters printed). To avoid ambiguity, it is preferable to
use an explicit value in the return statement, either as a variable or a
constant, such as @code{return 0}.
@end table
The complete set of warning options included in @option{-Wall} can be
found in the GCC Reference Manual ``@cite{Using GCC}'' (@pxref{Further
reading}). The options included in @option{-Wall} have the common
characteristic that they report constructions which are always wrong, or
can easily be rewritten in an unambiguously correct way. This is why
they are so useful---any warning produced by @option{-Wall} can be
taken as an indication of a potentially serious problem.
@node Additional warning options
@section Additional warning options
@cindex additional warning options
@cindex warning options, additional
GCC provides many other warning options that are not included in
@option{-Wall} but are often useful. Typically these produce warnings
for source code which may be technically valid but is very likely to
cause problems. The criteria for these options are based on experience
of common errors---they are not included in @option{-Wall} because
they only indicate possibly problematic or ``suspicious'' code.
Since these warnings can be issued for valid code it is not necessary to
compile with them all the time. It is more appropriate to use them
periodically and review the results, checking for anything unexpected,
or to enable them for some programs or files.
@table @asis
@item @option{-W}
@cindex common errors, not included with @option{-Wall}
@cindex @option{-W} option, enable additional warnings
@cindex @option{W} option, enable additional warnings
@cindex warnings, additional with @option{-W}
@cindex warning option, @option{-W} additional warnings
This is a general option similar to @option{-Wall} which warns about a
selection of common programming errors, such as functions which can
return without a value (also known as ``falling off the end of the
function body''), and comparisons between signed and unsigned values.
For example, the following function tests whether an unsigned integer is
negative (which is impossible, of course):
@example
@verbatiminclude w.c
@end example
@noindent
Compiling this function with @option{-Wall} does not produce a warning,
@example
$ gcc -Wall -c w.c
@end example
@noindent
but does give a warning with @option{-W}:
@cindex comparison of expression always true/false warning
@example
$ gcc -W -c w.c
w.c: In function `foo':
w.c:4: warning: comparison of unsigned
expression < 0 is always false
@end example
@noindent
In practice, the options @option{-W} and @option{-Wall} are normally used
together.
@item @option{-Wconversion}
@cindex type conversions, warning of
@cindex conversions between types, warning of
@cindex unsigned variable converted to signed, warning of
@cindex signed variable converted to unsigned, warning of
@cindex @option{-Wconversion} option, warn about type conversions
@cindex @option{Wconversion} option, warn about type conversions
This option warns about implicit type conversions that could cause
unexpected results, such as conversions between floating-point and
integer types, between signed and unsigned types and between types of
different width (e.g. long and short integers). Conversions can occur
in expressions and assignments, and in calls to functions if the
types of the arguments do not match those specified in the prototype.
For example, the integer absolute value function @code{int abs(int i)}
is easily confused with the corresponding floating-point function
@code{double fabs(double x)}. This can lead to incorrect results, as
shown in the following program:
@example
@verbatiminclude wabs.c
@end example
@noindent
Compiling this function with @option{-Wall} does not produce a warning,
@example
$ gcc -Wall wabs.c
$ ./a.out
x = -3.14 |x| = 3 @r{(incorrect)}
@end example
@noindent
but does give a warning with @option{-Wconversion}:
@example
gcc -Wall -Wconversion wabs.c
wabs.c: In function `main':
wabs.c:8: warning: passing arg 1 of `abs' as
integer rather than floating due to prototype
@end example
The @option{-Wconversion} option also catches errors such as the
assignment of a negative value to an unsigned variable, as in the
following code,
@example
unsigned int x = -1;
@end example
@noindent
@cindex casts, used to avoid conversion warnings
@cindex unsigned integer, casting
@cindex signed integer, casting
This is technically allowed by the ANSI/ISO C standard (with the
negative integer being converted to a positive integer, according to the
machine representation) but could be a simple programming error. If you
need to perform such a conversion you can use an explicit cast, such as
@code{(unsigned int)-1}, to avoid any warnings from this option. On
two's-complement machines the cast of @math{-1} gives the maximum number
that can be represented by an unsigned integer.
@item @option{-Wshadow}
@cindex shadowing of variables
@cindex variable shadowing
@cindex @option{-Wshadow} option, warn about shadowed variables
@cindex @option{Wshadow} option, warn about shadowed variables
This option warns about the redeclaration of a variable name in a scope
where it has already been declared. This is referred to as variable
@dfn{shadowing}, and causes confusion about which occurrence of the
variable corresponds to which value.
The following function declares a local variable @code{y} that shadows
the declaration in the body of the function:
@example
@verbatiminclude shadow.c
@end example
@noindent
This is valid ANSI/ISO C, where the return value is 1. The shadowing of
the variable @code{y} might make it seem (incorrectly) that the return
value is @code{x}, when looking at the line @code{y = x} (especially in
a large and complicated function).
Shadowing can also occur for function names. For example, the following
program attempts to define a variable @code{sin} which shadows the
standard function @code{sin(x)}.
@example
@verbatiminclude shadow2.c
@end example
@noindent
This error will be detected by the @option{-Wshadow} option.
@item @option{-Wcast-qual}
@cindex qualifiers, warning about overriding by casts
@cindex @code{const}, warning about overriding by casts
@cindex @option{-Wcast-qual} option, warn about casts removing qualifiers
@cindex @option{Wcast-qual} option, warn about casts removing qualifiers
This option warns about pointers that are cast to remove a type
qualifier, such as @code{const}. For example, the following function
discards the @code{const} qualifier from its input argument, allowing it
to be overwritten:
@example
@verbatiminclude castqual.c
@end example
@noindent
The modification of the original contents of @code{str} is a
violation of its @code{const} property. This option will warn about the
improper cast of the variable @code{str} which allows the string to
be modified.
@item @option{-Wwrite-strings}
@cindex writable string constants, disabling
@cindex constant strings, compile-time warnings
@cindex @option{-Wwrite-strings} option, warning for modified string constants
@cindex @option{Wwrite-strings} option, warning for modified string constants
This option implicitly gives all string constants defined in the program
a @code{const} qualifier, causing a compile-time warning if there is an
attempt to overwrite them. The result of modifying a string constant is
not defined by the ANSI/ISO standard, and the use of writable string
constants is deprecated in GCC.
@cindex K&R dialect of C, warnings of different behavior
@cindex Traditional C (K&R), warnings of different behavior
@cindex @option{-Wtraditional} option, warn about traditional C
@cindex @option{Wtraditional} option, warn about traditional C
@item @option{-Wtraditional}
This option warns about parts of the code which would be interpreted
differently by an ANSI/ISO compiler and a ``traditional'' pre-ANSI
compiler.@footnote{The traditional form of the C language was described
in the original C reference manual ``@cite{The C Programming Language
(First Edition)}'' by Kernighan and Ritchie.} When maintaining legacy
software it may be necessary to investigate whether the traditional or
ANSI/ISO interpretation was intended in the original code for warnings
generated by this option.
@end table
@noindent
@cindex warnings, promoting to errors
@cindex compilation, stopping on warning
@cindex @option{-Werror} option, convert warnings to errors
@cindex @option{Werror} option, convert warnings to errors
The options above produce diagnostic warning messages, but allow the
compilation to continue and produce an object file or executable. For
large programs it can be desirable to catch all the warnings by stopping
the compilation whenever a warning is generated. The @option{-Werror}
option changes the default behavior by converting warnings into errors,
stopping the compilation whenever a warning occurs.
@node Recommended warning options
@section Recommended warning options
The following options are a good choice for finding problems in C and
C++ programs:
@example
$ gcc -ansi -pedantic -Wall -W -Wconversion
-Wshadow -Wcast-qual -Wwrite-strings
@end example
@noindent
While this list is not exhaustive, regular use of these options will
catch many common errors.
@node Using the preprocessor
@chapter Using the preprocessor
@cindex @code{cpp}, C preprocessor
@cindex preprocessor, using
This chapter describes the use of the GNU C preprocessor @code{cpp},
which is part of the GCC package. The preprocessor expands macros in
source files before they are compiled. It is automatically called
whenever GCC processes a C or C++ program.@footnote{In recent versions
of GCC the preprocessor is integrated into the compiler, although a
separate @command{cpp} command is also provided.}
@menu
* Defining macros::
* Macros with values::
* Preprocessing source files::
@end menu
@node Defining macros
@section Defining macros
@cindex defining macros
@cindex macros, defining in preprocessor
@cindex @code{#define}, preprocessor directive
@cindex @code{#ifdef}, preprocessor directive
The following program demonstrates the most common use of the C
preprocessor. It uses the preprocessor conditional @code{#ifdef} to
check whether a macro is defined:
@example
@verbatiminclude dtest.c
@end example
@noindent
When the macro is defined, the preprocessor includes the corresponding
code up to the closing @code{#endif} command. In this example, the
macro which is tested is called @code{TEST}, and the conditional part of
the source code is a @code{printf} statement which prints the message
``@code{Test mode}''.
The @code{gcc} option @option{-D@var{NAME}} defines a preprocessor macro
@code{NAME} from the command line. If the program above is compiled
with the command-line option @option{-DTEST}, the macro @code{TEST} will
be defined and the resulting executable will print both messages:
@cindex @option{-D} option, define macro
@cindex @option{D} option, define macro
@example
$ gcc -Wall -DTEST dtest.c
$ ./a.out
Test mode
Running...
@end example
@noindent
If the same program is compiled without the @option{-D} option then the
``@code{Test mode}'' message is omitted from the source code after
preprocessing, and the final executable does not include the code for
it:
@example
$ gcc -Wall dtest.c
$ ./a.out
Running...
@end example
@noindent
@cindex namespace, reserved prefix for preprocessor
Macros are generally undefined, unless specified on the command line
with the option @option{-D}, or in a source file (or library header
file) with @code{#define}. Some macros are automatically defined by the
compiler---these typically use a reserved namespace beginning with a
double-underscore prefix @samp{__}.
The complete set of predefined macros can be listed by running the GNU
preprocessor @code{cpp} with the option @option{-dM} on an empty file:
@cindex predefined macros
@cindex macros, predefined
@cindex @option{-dM} option, list predefined macros
@cindex @option{dM} option, list predefined macros
@example
$ cpp -dM /dev/null
#define __i386__ 1
#define __i386 1
#define i386 1
#define __unix 1
#define __unix__ 1
#define __ELF__ 1
#define unix 1
.......
@end example
@noindent
Note that this list includes a small number of system-specific macros
defined by @code{gcc} which do not use the double-underscore prefix.
These non-standard macros can be disabled with the @option{-ansi} option of
@code{gcc}.
@cindex system-specific predefined macros
@node Macros with values
@section Macros with values
@cindex value, of macro
@cindex macros, defined with value
In addition to being defined, a macro can also be given a
value. This value is inserted into the source code at each point where
the macro occurs. The following program uses a macro @code{NUM}, to
represent a number which will be printed:
@example
@verbatiminclude dtestval.c
@end example
@noindent
Note that macros are not expanded inside strings---only the
occurrence of @code{NUM} outside the string is substituted by the
preprocessor.
To define a macro with a value, the @option{-D} command-line option can
be used in the form @option{-D@var{NAME}=@var{VALUE}}. For example, the
following command line defines @code{NUM} to be 100 when compiling the
program above:
@example
$ gcc -Wall -DNUM=100 dtestval.c
$ ./a.out
Value of NUM is 100
@end example
@noindent
This example uses a number, but a macro can take values of any form.
Whatever the value of the macro is, it is inserted directly into the
source code at the point where the macro name occurs. For example, the
following definition expands the occurrences of @code{NUM} to @code{2+2}
during preprocessing:
@example
$ gcc -Wall -DNUM="2+2" dtestval.c
$ ./a.out
Value of NUM is 4
@end example
@noindent
After the preprocessor has made the substitution @code{NUM @expansion{}
2+2} this is equivalent to compiling the following program:
@example
@verbatiminclude dtestval2.c
@end example
@noindent
@noindent
Note that it is a good idea to surround macros by parentheses whenever
they are part of an expression. For example, the following program uses
parentheses to ensure the correct precedence for the multiplication
@code{10*NUM}:
@cindex precedence, when using preprocessor
@example
@verbatiminclude dtestval3.c
@end example
@noindent
With these parentheses, it produces the expected result when compiled
with the same command line as above:
@example
$ gcc -Wall -DNUM="2+2" dtestmul10.c
$ ./a.out
Ten times NUM is 40
@end example
@noindent
Without parentheses, the program would produce the value @code{22} from
the literal form of the expression @code{10*2+2 = 22}, instead of the
desired value @code{10*(2+2) = 40}.
When a macro is defined with @option{-D} alone, @code{gcc} uses a default
value of @code{1}. For example, compiling the original test program
with the option @option{-DNUM} generates an executable which produces the
following output:
@cindex default value, of macro defined with @option{-D}
@cindex macros, default value of
@cindex preprocessor macros, default value of
@example
$ gcc -Wall -DNUM dtestval.c
$ ./a.out
Value of NUM is 1
@end example
@noindent
@cindex quotes, for defining empty macro
A macro can be defined with an empty value using quotes on the command line,
@code{-D@var{NAME}=""}. Such a macro is still treated as @i{defined} by
conditionals such as @code{#ifdef}, but expands to nothing.
@cindex empty macro, compared with undefined macro
@cindex undefined macro, compared with empty macro
A macro containing quotes can be defined using shell-escaped quote
characters. For example, the command-line option
@code{-DMESSAGE='"Hello, World!"'} defines a macro @code{MESSAGE} which
expands to the sequence of characters @code{"Hello, World!"}. The outer
shell-quotes @code{'...'} protect the C-quotes of the string
@code{"Hello, World!"}. For an explanation of the different types of
quoting and escaping used in the shell see the ``@cite{GNU Bash
Reference Manual}'', @ref{Further reading}.
@cindex shell quoting
@node Preprocessing source files
@section Preprocessing source files
@cindex @option{-E} option, preprocess source files
@cindex @option{E} option, preprocess source files
@cindex preprocessing source files, @option{-E} option
It is possible to see the effect of the preprocessor on source files
directly, using the @option{-E} option of @code{gcc}. For example, the
file below defines and uses a macro @code{TEST}:
@example
@verbatiminclude test.c
@end example
@noindent
If this file is called @file{test.c} the effect of the preprocessor
can be seen with the following command line:
@example
$ gcc -E test.c
# 1 "test.c"
const char str[] = "Hello, World!" ;
@end example
@noindent
The @option{-E} option causes @code{gcc} to run the preprocessor,
display the expanded output, and then exit without compiling the
resulting source code. The value of the macro @code{TEST} is
substituted directly into the output, producing the sequence of
characters @code{const char str[] = "Hello, World!" ;}.
@cindex line numbers, recorded in preprocessed files
The preprocessor also inserts lines recording the source file and line
numbers in the form @code{# @var{line-number} "@var{source-file}"}, to
aid in debugging and allow the compiler to issue error messages
referring to this information. These lines do not affect the program
itself.
The ability to see the preprocessed source files can be useful
for examining the effect of system header files, and finding declarations
of system functions. The following program includes the header file
@file{stdio.h} to obtain the declaration of the function @code{printf}:
@example
@verbatiminclude hello.c
@end example
@noindent
It is possible to see the declarations from the included header file by
preprocessing the file with @code{gcc -E}:
@example
$ gcc -E hello.c
@end example
@noindent
On a GNU system, this produces output similar to the following:
@example
# 1 "hello.c"
# 1 "/usr/include/stdio.h" 1 3
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
extern int fprintf (FILE * __stream,
const char * __format, ...) ;
extern int printf (const char * __format, ...) ;
@r{@i{[ ... additional declarations ... ]}}
# 1 "hello.c" 2
int
main (void)
@{
printf ("Hello, world!\n");
return 0;
@}
@end example
@noindent
The preprocessed system header files usually generate a lot of
output. This can be redirected to a file, or saved more conveniently
using the @code{gcc} @option{-save-temps} option:
@cindex @option{-save-temps} option, keeps intermediate files
@cindex @option{save-temps} option, keeps intermediate files
@cindex preprocessed files, keeping
@cindex intermediate files, keeping
@cindex temporary files, keeping
@example
$ gcc -c -save-temps hello.c
@end example
@noindent
After running this command, the preprocessed output will be available in
the file @file{hello.i}. The @option{-save-temps} option also saves
@file{.s} assembly files and @file{.o} object files in addition to
preprocessed @file{.i} files.
@node Compiling for debugging
@chapter Compiling for debugging
@cindex debugging, compilation flags
@cindex @option{-g} option, enable debugging
@cindex @option{g} option, enable debugging
@cindex compilation, for debugging
Normally, an executable file does not contain any references to the
original program source code, such as variable names or
line-numbers---the executable file is simply the sequence of machine
code instructions produced by the compiler. This is insufficient for
debugging, since there is no easy way to find the cause of an error if
the program crashes.
@cindex @code{gdb}
@cindex debugging, with @code{gdb}
@cindex GNU debugger, @code{gdb}
@cindex symbol table
@cindex executable, symbol table stored in
GCC provides the @option{-g} @dfn{debug option} to store additional
debugging information in object files and executables. This debugging
information allows errors to be traced back from a specific machine
instruction to the corresponding line in the original source file. The
execution of a program compiled with @option{-g} can also be followed in a
debugger, such as the GNU Debugger @code{gdb} (for more information, see
``@cite{Debugging with GDB: The GNU Source-Level Debugger}'',
@ref{Further reading}). Using a debugger allows the values of
variables to be examined while the program is running.
The debug compilation option works by storing the names and source
code line-numbers of functions and variables in a @dfn{symbol table}
in the object file or executable.
@menu
* Examining core files::
* Displaying a backtrace::
* Setting a breakpoint::
* Stepping through the program::
* Modifying variables::
* Continuing execution::
* More information about GDB::
@end menu
@node Examining core files
@section Examining core files
@cindex core file, examining
@cindex crashes, saved in core file
@cindex program crashes, saved in core file
@cindex examining core files
In addition to allowing programs to be run under the debugger, an
important benefit of the @option{-g} option is the ability to examine
the cause of a program crash from a ``core dump''.
@cindex termination, abnormal (@code{core dumped})
When a program exits abnormally (i.e. crashes) the operating system can
write out a @dfn{core file} (usually named @file{core}) which contains
the in-memory state of the program at the time it crashed. This file is
often referred to as a @dfn{core dump}.@footnote{The terminology dates
back to the time of magnetic core memory.} Combined with information from the
symbol table produced by @option{-g}, the core dump can be used to find
the line where the program stopped, and the values of its variables at
that point.
@cindex deployment, options for
This is useful both during the development of software and after
deployment---it allows problems to be investigated when a program has
crashed ``in the field''.
Here is a simple program containing an invalid memory access bug, which
we will use to produce a core file:
@example
@verbatiminclude null.c
@end example
@noindent
@cindex dereferencing, null pointer
@cindex null pointer
@cindex bug, example of
The program attempts to dereference a null pointer @code{p}, which is an
invalid operation. On most systems, this will cause a
crash. @footnote{Historically, a null pointer corresponded to memory
location 0, which is typically restricted to the operating system
kernel. In practice this is not always how a null pointer works, but
the result is usually the same.}
In order to be able to find the cause of the crash later, we will need
to compile the program with the @option{-g} option:
@example
$ gcc -Wall -g null.c
@end example
@noindent
Note that a null pointer will only cause a problem at run-time, so the
option @option{-Wall} does not produce any warnings.
Running the executable file on an x86 GNU/Linux system will cause the
operating system to terminate the program abnormally:
@cindex segmentation fault
@example
$ ./a.out
Segmentation fault (core dumped)
@end example
@noindent
Whenever the error message @samp{core dumped} is displayed, the
operating system should produce a file called @file{core} in the current
directory.@footnote{Some systems, such as FreeBSD and Solaris, can also
be configured to write core files in specific directories,
e.g. @file{/var/coredumps/}, using the @code{sysctl} or @code{coreadm}
commands.} This core file contains a complete copy of the pages of
memory used by the program at the time it was terminated. Incidentally,
the term @dfn{segmentation fault} refers to the fact that the program
tried to access a restricted memory ``segment'' outside the area of
memory which had been allocated to it.
@cindex core file, not produced
@cindex @command{ulimit} command
Some systems are configured not to write core files by default, since
the files can be large and rapidly fill up the available disk space on a
system. In the @cite{GNU Bash} shell the command @code{ulimit -c}
controls the maximum size of core files. If the size limit is zero, no
core files are produced. The current size limit can be shown by typing
the following command:
@cindex @code{tcsh}, limit command
@example
$ ulimit -c
0
@end example
@noindent
If the result is zero, as shown above, then it can be increased with the
following command to allow core files of any size to be
written:@footnote{This example uses the @code{ulimit} command in the GNU
Bash shell. On other systems the usage of the @code{ulimit} command may
vary, or have a different name (the @code{tcsh} shell uses the
@code{limit} command instead). The size limit for core files can also
be set to a specific value in kilobytes.}
@example
$ ulimit -c unlimited
@end example
@noindent
Note that this setting only applies to the current shell. To set the
limit for future sessions the command should be placed in an appropriate
login file, such as @file{.bash_profile} for the GNU Bash shell.
@cindex @code{bash} profile file
@cindex core file, examining
@cindex @code{gdb}, debugging core file with
Core files can be loaded into the GNU Debugger @code{gdb} with the
following command:
@example
$ gdb @var{EXECUTABLE-FILE} @var{CORE-FILE}
@end example
@noindent
Note that both the original executable file and the core file are
required for debugging---it is not possible to debug a core file without
the corresponding executable. In this example, we can load the
executable and core file with the command:
@example
$ gdb a.out core
@end example
@noindent
The debugger immediately begins printing diagnostic information, and
shows a listing of the line where the program crashed (line 13):
@example
$ gdb a.out core
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
#0 0x080483ed in foo (p=0x0) at null.c:13
13 int y = *p;
(gdb)
@end example
@noindent
The final line @code{(gdb)} is the GNU Debugger prompt---it indicates
that further commands can be entered at this point.
To investigate the cause of the crash, we display the value of the
pointer @code{p} using the debugger @code{print} command:
@cindex @code{print} debugger command
@example
(gdb) print p
$1 = (int *) 0x0
@end example
@noindent
This shows that @code{p} is a null pointer (@code{0x0}) of type
@samp{int *}, so we know that dereferencing it with the expression
@code{*p} in this line has caused the crash.
@node Displaying a backtrace
@section Displaying a backtrace
@cindex displaying a backtrace
@cindex backtrace, displaying
@cindex stack backtrace, displaying
@cindex @code{backtrace}, debugger command
The debugger can also show the function calls and arguments up to the
current point of execution---this is called a @dfn{stack backtrace}
and is displayed with the command @code{backtrace}:
@example
(gdb) backtrace
#0 0x080483ed in foo (p=0x0) at null.c:13
#1 0x080483d9 in main () at null.c:7
@end example
@noindent
In this case, the backtrace shows that the crash occurred at line 13
after the function @code{foo} was called from @code{main} with an argument of
@code{p=0x0} at line 7 in @file{null.c}. It is possible to move to
different levels in the stack trace, and examine their variables, using
the debugger commands @code{up} and @code{down}.
@node Setting a breakpoint
@section Setting a breakpoint
@cindex @code{break}, command in @code{gdb}
@cindex breakpoints, defined
@cindex stopping execution, with breakpoints in @code{gdb}
A @dfn{breakpoint} stops the execution of a program and returns control
to the debugger, where its variables and memory can be examined before
continuing. Breakpoints can be set for specific functions, lines or
memory locations with the @code{break} command.
To set a breakpoint on a specific function, use the command @code{break
@var{function-name}}. For example, the following command sets a
breakpoint at the start of the @code{main} function in the program
above:
@example
$ gdb a.out
(gdb) break main
Breakpoint 1 at 0x80483c6: file null.c, line 6.
@end example
@noindent
The debugger will now take control of the program when the function
@code{main} is called. Since the @code{main} function is the first
function to be executed in a C program the program will stop immediately
when it is run:
@example
(gdb) run
Starting program: a.out
Breakpoint 1, main () at null.c:6
6 int *p = 0; /* null pointer */
(gdb)
@end example
@noindent
The display shows the line that will be executed next (the line number
is shown on the left). The breakpoint stops the program @emph{before}
the line is executed, so at this stage the pointer @code{p} is
undefined and has not yet been set to zero.
@node Stepping through the program
@section Stepping through the program
@cindex @code{step}, command in @code{gdb}
@cindex @code{next}, command in @code{gdb}
To move forward and execute the line displayed above, use the command
@code{step}:
@example
(gdb) step
7 return foo (p);
@end example
@noindent
After executing line 6, the debugger displays the next line to be
executed. The pointer @code{p} will now have been set to zero (null):
@example
(gdb) print p
$1 = (int *) 0x0
@end example
@noindent
The command @code{step} will follow the execution of the program
interactively through any functions that are called in the current
line. If you want to move forward without tracing these calls,
use the command @code{next} instead.
@node Modifying variables
@section Modifying variables
@cindex @code{set}, command in @code{gdb}
To temporarily fix the null pointer bug discovered above, we can change
the value of @code{p} in the running program using the @code{set
variable} command.
Variables can be set to a specific value, or to the result of an
expression, which may include function calls. This powerful feature
allows functions in a program to be tested interactively through the
debugger.
In this case we will interactively allocate some memory for the pointer
@code{p} using the function @code{malloc}, storing the value 255 in the
resulting location:
@example
(gdb) set variable p = malloc(sizeof(int))
(gdb) print p
$2 = (int *) 0x40013f98 @r{(address allocated by @code{malloc})}
(gdb) set variable *p = 255
(gdb) print *p
$3 = 255
@end example
@noindent
If we now continue stepping through the program with the new value of
@code{p} the previous segmentation fault will not occur:
@example
(gdb) step
foo (p=0x40013f98) at null.c:13
13 int y = *p;
(gdb) step
14 return y;
@end example
@node Continuing execution
@section Continuing execution
@cindex @code{finish}, command in @code{gdb}
@cindex @code{continue}, command in @code{gdb}
The command @code{finish} continues execution up to the end of the
current function, displaying the return value:
@example
(gdb) finish
Run till exit from #0 0x08048400 in foo (p=0x40013f98)
at null.c:15
0x080483d9 in main () at null.c:7
7 return foo (p);
Value returned is $13 = 255
@end example
@noindent
@cindex exit code, displayed in @code{gdb}
To continue execution until the program exits (or hits the next
breakpoint) use the command @code{continue},
@example
(gdb) continue
Continuing.
Program exited with code 0377.
@end example
@noindent
Note that the exit code is shown in octal (0377 base 8 = 255 in base 10).
@node More information about GDB
@section More information
@cindex Emacs, @code{gdb} mode
@cindex @code{gdb}, Emacs mode
@cindex @code{gdb}, graphical interface
@cindex Insight, graphical interface for @code{gdb}
For simplicity, the examples in this chapter demonstrate how to use
@code{gdb} on the command-line. There are more powerful ways to debug a
program interactively using tools such as Emacs @sc{gdb} mode (@kbd{M-x
gdb}), @sc{ddd} or @sc{insight}, graphical interfaces to @code{gdb}.
Links to these programs can be found on the publisher's webpage for this
book.@footnote{@uref{http://www.network-theory.co.uk/gcc/intro/}}
A complete description of all the commands available in @code{gdb} can
be found in the manual ``@cite{Debugging with GDB: The GNU Source-Level
Debugger}'' (@pxref{Further reading}).
@node Compiling with optimization
@chapter Compiling with optimization
@cindex optimization, explanation of
@cindex compiling with optimization
GCC is an @dfn{optimizing} compiler. It provides a wide range of
options which aim to increase the speed, or reduce the size, of the
executable files it generates.
Optimization is a complex process. For each high-level command in the
source code there are usually many possible combinations of machine
instructions that can be used to achieve the appropriate final result.
The compiler must consider these possibilities and choose among them.
In general, different code must be generated for different processors,
as they use incompatible assembly and machine languages. Each type of
processor also has its own characteristics---some CPUs provide a large
number of @dfn{registers} for holding intermediate results of
calculations, while others must store and fetch intermediate results
from memory. Appropriate code must be generated in each case.
Furthermore, different amounts of time are needed for different
instructions, depending on how they are ordered. GCC takes all these factors
into account and tries to produce the fastest executable for a given
system when compiling with optimization.
@menu
* Source-level optimization::
* Speed-space tradeoffs::
* Scheduling::
* Optimization levels::
* Optimization examples::
* Optimization and debugging::
* Optimization and compiler warnings::
@end menu
@node Source-level optimization
@section Source-level optimization
@cindex source-level optimization
The first form of optimization used by GCC occurs at the source-code
level, and does not require any knowledge of the machine instructions.
There are many source-level optimization techniques---this section
describes two common types: @dfn{common subexpression elimination} and
@dfn{function inlining}.
@subsection Common subexpression elimination
@cindex common subexpression elimination, optimization
@cindex optimization, common subexpression elimination
@cindex subexpression elimination, optimization
@cindex elimination, of common subexpressions
One method of source-level optimization which is easy to understand
involves computing an expression in the source code with fewer
instructions, by reusing already-computed results. For example, the
following assignment:
@example
x = cos(v)*(1+sin(u/2)) + sin(w)*(1-sin(u/2))
@end example
@noindent
can be rewritten with a temporary variable @code{t} to eliminate an
unnecessary extra evaluation of the term @code{sin(u/2)}:
@example
t = sin(u/2)
x = cos(v)*(1+t) + sin(w)*(1-t)
@end example
@noindent
This rewriting is called @dfn{common subexpression elimination} (CSE),
and is performed automatically when optimization is turned
on.@footnote{Temporary values introduced by the compiler during common
subexpression elimination are only used internally, and do not affect
real variables. The name of the temporary variable @samp{t} shown above
is only used as an illustration.} Common subexpression elimination is
powerful, because it simultaneously increases the speed and reduces the
size of the code.
@subsection Function inlining
@cindex function inlining, example of optimization
@cindex inlining, example of optimization
@comment An example of speed-space tradeoffs occurs with an optimization called
@comment @dfn{function inlining}.
Another type of source-level optimization, called @dfn{function
inlining}, increases the efficiency of frequently-called functions.
Whenever a function is used, a certain amount of extra time is required
for the CPU to carry out the call: it must store the function arguments
in the appropriate registers and memory locations, jump to the start of
the function (bringing the appropriate virtual memory pages into
physical memory or the CPU cache if necessary), begin executing the
code, and then return to the original point of execution when the
function call is complete. This additional work is referred to as
@dfn{function-call overhead}. Function inlining eliminates this
overhead by replacing calls to a function by the code of the function
itself (known as placing the code @dfn{in-line}).
@cindex function-call overhead
@cindex overhead, from function call
In most cases, function-call overhead is a negligible fraction of the
total run-time of a program. It can become significant only when there
are functions which contain relatively few instructions, and these
functions account for a substantial fraction of the run-time---in this
case the overhead then becomes a large proportion of the total run-time.
Inlining is always favorable if there is only one point of invocation of
a function. It is also unconditionally better if the invocation of a
function requires more instructions (memory) than moving the body of the
function in-line. This is a common situation for simple accessor
functions in C++, which can benefit greatly from inlining. Moreover,
inlining may facilitate further optimizations, such as common
subexpression elimination, by merging several separate functions into a
single large function.
The following function @code{sq(x)} is a typical example of a function
that would benefit from being inlined. It computes @math{x^2}, the
square of its argument @math{x}:
@example
double
sq (double x)
@{
return x * x;
@}
@end example
@noindent
This function is small, so the overhead of calling it is comparable to
the time taken to execute the single multiplication carried out by the
function itself. If this function is used inside a loop, such as the
one below, then the function-call overhead would become substantial:
@example
for (i = 0; i < 1000000; i++)
@{
sum += sq (i + 0.5);
@}
@end example
@noindent
Optimization with inlining replaces the inner loop of the program with
the body of the function, giving the following code:
@example
for (i = 0; i < 1000000; i++)
@{
double t = (i + 0.5); /* temporary variable */
sum += t * t;
@}
@end example
@noindent
Eliminating the function call and performing the multiplication
@dfn{in-line} allows the loop to run with maximum efficiency.
GCC selects functions for inlining using a number of heuristics, such as
the function being suitably small. As an optimization, inlining is
carried out only within each object file. The @code{inline} keyword can
be used to request explicitly that a specific function should be inlined
wherever possible, including its use in other files.@footnote{In this
case, the definition of the inline function must be made available to
the other files (e.g. in a header file).} The GCC Reference
Manual ``@cite{Using GCC}'' provides full details of the @code{inline}
keyword, and its use with the @code{static} and @code{extern} qualifiers
to control the linkage of explicitly inlined functions (@pxref{Further
reading}).
@node Speed-space tradeoffs
@section Speed-space tradeoffs
@cindex speed-space tradeoffs, in optimization
@cindex optimization, speed-space tradeoffs
@cindex tradeoffs, between speed and space in optimization
@cindex space vs speed, tradeoff in optimization
While some forms of optimization, such as common subexpression
elimination, are able to increase the speed and reduce the size of a
program simultaneously, other types of optimization produce faster code
at the expense of increasing the size of the executable. This choice
between speed and memory is referred to as a @dfn{speed-space tradeoff}.
Optimizations with a speed-space tradeoff can also be used in reverse
to make an executable smaller, at the expense of making it run slower.
@subsection Loop unrolling
@cindex loop unrolling, optimization
@cindex optimization, loop unrolling
@cindex unrolling, of loops (optimization)
A prime example of an optimization with a speed-space tradeoff is
@dfn{loop unrolling}. This form of optimization increases the speed of
loops by eliminating the ``end of loop'' condition on each iteration.
For example, the following loop from 0 to 7 tests the condition @code{i
< 8} on each iteration:
@example
for (i = 0; i < 8; i++)
@{
y[i] = i;
@}
@end example
@noindent
At the end of the loop, this test will have been performed 9 times, and
a large fraction of the run time will have been spent checking it.
A more efficient way to write the same code is simply to @dfn{unroll the
loop} and execute the assignments directly:
@example
y[0] = 0;
y[1] = 1;
y[2] = 2;
y[3] = 3;
y[4] = 4;
y[5] = 5;
y[6] = 6;
y[7] = 7;
@end example
@noindent
This form of the code does not require any tests, and executes at
maximum speed. Since each assignment is independent, it also allows the
compiler to use parallelism on processors that support it. Loop
unrolling is an optimization that increases the speed of the resulting
executable but also generally increases its size (unless the loop is
very short, with only one or two iterations, for example).
Loop unrolling is also possible when the upper bound of the loop is
unknown, provided the start and end conditions are handled correctly.
For example, the same loop with an arbitrary upper bound,
@example
for (i = 0; i < n; i++)
@{
y[i] = i;
@}
@end example
@noindent
can be rewritten by the compiler as follows:
@example
for (i = 0; i < (n % 2); i++)
@{
y[i] = i;
@}
for ( ; i + 1 < n; i += 2) /* no initializer */
@{
y[i] = i;
y[i+1] = i+1;
@}
@end example
@noindent
The first loop handles the case @code{i = 0} when @code{n} is odd, and
the second loop handles all the remaining iterations. Note that the
second loop does not use an initializer in the first argument of the
@code{for} statement, since it continues where the first loop
finishes. The assignments in the second loop can be parallelized, and
the overall number of tests is reduced by a factor of 2 (approximately).
Higher factors can be achieved by unrolling more assignments inside the
loop, at the cost of greater code size.
@node Scheduling
@section Scheduling
@cindex scheduling, stage of optimization
@cindex instruction scheduling, optimization
@cindex pipelining, explanation of
The lowest level of optimization is @dfn{scheduling}, in which the
compiler determines the best ordering of individual instructions. Most
CPUs allow one or more new instructions to start executing before others
have finished. Many CPUs also support @dfn{pipelining}, where multiple
instructions execute in parallel on the same CPU.
When scheduling is enabled, instructions must be arranged so that their
results become available to later instructions at the right time, and to
allow for maximum parallel execution. Scheduling improves the speed of
an executable without increasing its size, but requires additional
memory and time in the compilation process itself (due to its
complexity).
@node Optimization levels
@section Optimization levels
@cindex optimization, compiling with @option{-O}
@cindex optimization, levels of
@cindex levels of optimization
@cindex @option{O} option, optimization level
In order to control compilation-time and compiler memory usage, and the
trade-offs between speed and space for the resulting executable, GCC
provides a range of general optimization levels, numbered from 0--3, as
well as individual options for specific types of optimization.
An optimization level is chosen with the command line option
@option{-O@var{LEVEL}}, where @code{@var{LEVEL}} is a number from 0 to 3.
The effects of the different optimization levels are described below:
@table @asis
@item @option{-O0} or @r{no @option{-O} option} (default)
@cindex @option{-O0} option, optimization level zero
@cindex unoptimized code (@option{-O0})
At this optimization level GCC does not perform any optimization and
compiles the source code in the most straightforward way possible. Each
command in the source code is converted directly to the corresponding
instructions in the executable file, without rearrangement. This is the
best option to use when debugging a program and is the default
if no optimization level option is specified.
@item @option{-O1} @r{or} @option{-O}
@cindex @option{-O1} option, optimization level one
This level turns on the most common forms of optimization that do not
require any speed-space tradeoffs. With this option the resulting
executables should be smaller and faster than with @option{-O0}. The
more expensive optimizations, such as instruction scheduling, are not
used at this level.
Compiling with the option @option{-O1} can often take less time than
compiling with @option{-O0}, due to the reduced amounts of data that
need to be processed after simple optimizations.
@item @option{-O2}
@cindex @option{-O2} option, optimization level two
@cindex deployment, options for
This option turns on further optimizations, in addition to those used by
@option{-O1}. These additional optimizations include instruction
scheduling. Only optimizations that do not require any speed-space
tradeoffs are used, so the executable should not increase in size. The
compiler will take longer to compile programs and require more memory
than with @option{-O1}. This option is generally the best choice for
deployment of a program, because it provides maximum optimization
without increasing the executable size. It is the default optimization
level for releases of GNU packages.
@item @option{-O3}
@cindex @option{-O3} option, optimization level three
This option turns on more expensive optimizations, such as function
inlining, in addition to all the optimizations of the lower levels
@option{-O2} and @option{-O1}. The @option{-O3} optimization level may
increase the speed of the resulting executable, but can also increase
its size. Under some circumstances where these optimizations are not
favorable, this option might actually make a program slower.
@item @option{-funroll-loops}
@cindex @option{-funroll-loops} option, optimization by loop unrolling
@cindex @option{funroll-loops} option, optimization by loop unrolling
@cindex loop unrolling, optimization
@cindex optimization, loop unrolling
@cindex unrolling, of loops (optimization)
This option turns on loop-unrolling, and is independent of the other
optimization options. It will increase the size of an executable.
Whether or not this option produces a beneficial result has to be examined
on a case-by-case basis.
@item @option{-Os}
@cindex @option{-Os} option, optimization for size
@cindex optimization for size, @option{-Os}
@cindex size, optimization for, @option{-Os}
This option selects optimizations which reduce the size of an
executable. The aim of this option is to produce the smallest possible
executable, for systems constrained by memory or disk space. In some
cases a smaller executable will also run faster, due to better cache
usage.
@end table
It is important to remember that the benefit of optimization at the
highest levels must be weighed against the cost. The cost of
optimization includes greater complexity in debugging, and increased
time and memory requirements during compilation. For most purposes it
is satisfactory to use @option{-O0} for debugging, and @option{-O2} for
development and deployment.
@node Optimization examples
@section Examples
@cindex optimization, example of
The following program will be used to demonstrate the effects of
different optimization levels:
@example
@verbatiminclude optim.c
@end example
@noindent
@cindex benchmarking, with @code{time} command
@cindex @code{time} command, measuring run-time
@cindex run-time, measuring with @code{time} command
The main program contains a loop calling the @code{powern} function.
This function computes the @i{n}-th power of a floating point number by
repeated multiplication---it has been chosen because it is suitable for
both inlining and loop-unrolling. The run-time of the program can be
measured using the @code{time} command in the GNU Bash shell.
Here are some results for the program above, compiled on a 566@dmn{MHz}
Intel Celeron with 16@dmn{KB} L1-cache and 128@dmn{KB} L2-cache, using
GCC 3.3.1 on a GNU/Linux system:
@example
$ gcc -Wall -O0 test.c -lm
$ time ./a.out
real 0m13.388s
user 0m13.370s
sys 0m0.010s
$ gcc -Wall -O1 test.c -lm
$ time ./a.out
real 0m10.030s
user 0m10.030s
sys 0m0.000s
$ gcc -Wall -O2 test.c -lm
$ time ./a.out
real 0m8.388s
user 0m8.380s
sys 0m0.000s
$ gcc -Wall -O3 test.c -lm
$ time ./a.out
real 0m6.742s
user 0m6.730s
sys 0m0.000s
$ gcc -Wall -O3 -funroll-loops test.c -lm
$ time ./a.out
real 0m5.412s
user 0m5.390s
sys 0m0.000s
@end example
@noindent
The relevant entry in the output for comparing the speed of the
resulting executables is the @samp{user} time, which gives the actual
CPU time spent running the process. The other rows, @samp{real} and
@samp{sys}, record the total real time for the process to run (including
times where other processes were using the CPU) and the time spent
waiting for operating system calls. Although only one run is shown for
each case above, the benchmarks were executed several times to confirm
the results.
From the results it can be seen in this case that increasing the
optimization level with @option{-O1}, @option{-O2} and @option{-O3}
produces an increasing speedup, relative to the unoptimized code
compiled with @option{-O0}. The additional option
@option{-funroll-loops} produces a further speedup. The speed of the
program is more than doubled overall, when going from unoptimized code
to the highest level of optimization.
Note that for a small program such as this there can be considerable
variation between systems and compiler versions. For example, on a
Mobile 2.0@dmn{GHz} Intel Pentium 4M system the trend of the results
using the same version of GCC is similar except that the performance
with @option{-O2} is slightly worse than with @option{-O1}. This
illustrates an important point: optimizations may not necessarily make a
program faster in every case.
@node Optimization and debugging
@section Optimization and debugging
@cindex debugging, with optimization
@cindex optimization, with debugging
With GCC it is possible to use optimization in combination with the
debugging option @option{-g}. Many other compilers do not allow this.
When using debugging and optimization together, the internal
rearrangements carried out by the optimizer can make it difficult to see
what is going on when examining an optimized program in the debugger.
For example, temporary variables are often eliminated, and the ordering
of statements may be changed.
@cindex deployment, options for
However, when a program crashes unexpectedly, any debugging information
is better than none---so the use of @option{-g} is recommended for
optimized programs, both for development and deployment. The debugging
option @option{-g} is enabled by default for releases of GNU packages,
together with the optimization option @option{-O2}.
@node Optimization and compiler warnings
@section Optimization and compiler warnings
@cindex optimization, and compiler warnings
@cindex warnings, and optimization
When optimization is turned on, GCC can produce additional warnings that
do not appear when compiling without optimization.
@cindex data-flow analysis
As part of the optimization process, the compiler examines the use of all
variables and their initial values---this is referred to as
@dfn{data-flow analysis}. It forms the basis for other optimization
strategies, such as instruction scheduling. A side-effect of data-flow
analysis is that the compiler can detect the use of uninitialized
variables.
@cindex @option{-Wuninitialized} option, warn about uninitialized variables
@cindex @option{Wuninitialized} option, warn about uninitialized variables
The @option{-Wuninitialized} option (which is included in
@option{-Wall}) warns about variables that are read without being
initialized. It only works when the program is compiled with
optimization, so that data-flow analysis is enabled. The following function
contains an example of such a variable:
@example
@verbatiminclude uninit.c
@end example
@noindent
@cindex C/C++, risks of using
The function works correctly for most arguments, but has a bug when
@code{x} is zero---in this case the return value of the variable
@code{s} will be undefined.
Compiling the program with the @option{-Wall} option alone does not
produce any warnings, because data-flow analysis is not carried out
without optimization:
@example
$ gcc -Wall -c uninit.c
@end example
@noindent
To produce a warning, the program must be compiled with @option{-Wall} and
optimization simultaneously. In practice, the optimization level
@option{-O2} is needed to give good warnings:
@cindex uninitialized variable, warning of
@cindex variable, warning of uninitialized use
@example
$ gcc -Wall -O2 -c uninit.c
uninit.c: In function `sign':
uninit.c:4: warning: `s' might be used uninitialized
in this function
@end example
@noindent
This correctly detects the possibility of the variable @code{s} being
used without being defined.
Note that while GCC will usually find most uninitialized variables, it
does so using heuristics which will occasionally miss some complicated
cases or falsely warn about others. In the latter situation, it is often
possible to rewrite the relevant lines in a simpler way that removes the
warning and improves the readability of the source code.
@node Compiling a C++ program
@chapter Compiling a C++ program
@cindex C++, @code{g++} as a true compiler
@cindex translators, from C++ to C, compared with @code{g++}
This chapter describes how to use GCC to compile programs written in
C++, and the command-line options specific to that language.
The GNU C++ compiler provided by GCC is a true C++ compiler---it
compiles C++ source code directly into assembly language. Some other
C++ ``compilers'' are translators which convert C++ programs into C, and
then compile the resulting C program using an existing C compiler. A
true C++ compiler, such as GCC, is able to provide better support for
error reporting, debugging and optimization.
@menu
* Compiling a simple C++ program::
* C++ compilation options::
* Using the C++ standard library::
* Templates::
@end menu
@node Compiling a simple C++ program
@section Compiling a simple C++ program
@cindex C++, compiling a simple program with @code{g++}
@cindex @code{g++}, compiling C++ programs
@cindex compiling C++ programs with @code{g++}
@cindex simple C++ program, compiling
The procedure for compiling a C++ program is the same as for a C
program, but uses the command @code{g++} instead of @code{gcc}. Both
compilers are part of the GNU Compiler Collection.
@cindex Hello World program, in C++
To demonstrate the use of @code{g++}, here is a version of the @dfn{Hello
World} program written in C++:
@example
@verbatiminclude hello.cc
@end example
@noindent
The program can be compiled with the following command line:
@example
$ g++ -Wall hello.cc -o hello
@end example
@noindent
@cindex @code{.cc}, C++ file extension
@cindex @code{cc}, C++ file extension
@cindex @code{.cpp}, C++ file extension
@cindex @code{cpp}, C++ file extension
@cindex @code{.cxx}, C++ file extension
@cindex @code{cxx}, C++ file extension
@cindex extension, @code{.C}, C++ file
@cindex extension, @code{.cc}, C++ file
@cindex extension, @code{.cpp}, C++ file
@cindex extension, @code{.cxx}, C++ file
@cindex extension, @code{.C}, C++ file
@cindex file extension, @code{.C}, C++ file
@cindex file extension, @code{.cc}, C++ file
@cindex file extension, @code{.cpp}, C++ file
@cindex file extension, @code{.cxx}, C++ file
@cindex file extension, @code{.C}, C++ file
@cindex C++, file extensions
The C++ frontend of GCC uses many of the same the same options as the C
compiler @code{gcc}. It also supports some additional options for
controlling C++ language features, which will be described in this
chapter. Note that C++ source code should be given one of the valid C++
file extensions @file{.cc}, @file{.cpp}, @file{.cxx} or @file{.C} rather
than the @file{.c} extension used for C programs.
@cindex @option{-ansi} option, used with @code{g++}
@cindex @option{ansi} option, used with @code{g++}
@cindex ISO C++, controlled with @option{-ansi} option
@cindex running an executable file, C++
The resulting executable can be run in exactly same way as the C
version, simply by typing its filename:
@example
$ ./hello
Hello, world!
@end example
@noindent
The executable produces the same output as the C version of the program,
using @code{std::cout} instead of the C @code{printf} function. All the
options used in the @code{gcc} commands in previous chapters apply to
@code{g++} without change, as do the procedures for compiling and
linking files and libraries (using @code{g++} instead of @code{gcc}, of
course). One natural difference is that the @option{-ansi} option
requests compliance with the C++ standard, instead of the C standard, when
used with @code{g++}.
Note that programs using C++ object files must always be linked with
@code{g++}, in order to supply the appropriate C++ libraries.
Attempting to link a C++ object file with the C compiler @code{gcc} will
cause ``undefined reference'' errors for C++ standard library functions:
@cindex undefined reference to C++ function, due to linking with @code{gcc}
@example
$ g++ -Wall -c hello.cc
$ gcc hello.o @r{(should use @code{g++})}
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
@end example
@noindent
Undefined references to internal run-time library functions, such as
@code{__gxx_personality_v0}, are also a symptom of linking C++ object
files with @code{gcc} instead of @code{g++}. Linking the same object
file with @code{g++} supplies all the necessary C++ libraries and will
produce a working executable:
@example
$ g++ hello.o
$ ./a.out
Hello, world!
@end example
@noindent
@cindex @code{__gxx_personality_v0}, undefined reference error
@cindex @code{gxx_personality_v0}, undefined reference error
@cindex @code{gcc}, used inconsistently with @code{g++}
@cindex undefined reference error for @code{__gxx_personality_v0}
A point that sometimes causes confusion is that @code{gcc} will actually
compile C++ source code when it detects a C++ file extension, but cannot
then link the resulting object files.
@example
$ gcc -Wall -c hello.cc @r{(succeeds, even for C++)}
$ gcc hello.o
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
@end example
@noindent
To avoid this problem, use @code{g++} consistently for C++
programs and @code{gcc} for C programs.
@node C++ compilation options
@section C++ compilation options
Most GCC options can be used for both C and C++ programs, but there are
also a few options which are specific to each language. This section
describes some of the additional options, and enhancements to existing
options, that are available in @command{g++}.
@table @asis
@item @option{-Wall} and @option{-W}
When compiling with @code{g++}, the options @option{-Wall} and
@option{-W} include extra warnings specific to C++ (the warnings relate
to member functions and virtual classes). The use of these options is
always recommended while developing a program.
@item @option{-fno-default-inline}
@cindex @option{-fno-default-inline} option
@cindex @option{fno-default-inline} option
@cindex @option{no-default-inline} option
This option disables the default inlining of member functions defined in
the bodies of C++ classes. GCC normally inlines all such
functions when optimization is turned on, even if they do not explicitly
use the @code{inline} keyword. Select this option if you prefer to
control inlining yourself, or want to set a breakpoint on member
functions that would otherwise be inlined (since it is not possible to
set a breakpoint on an inlined function).
@item @option{-Weffc++}
@cindex @option{-Weffc++} option
@cindex @option{Weffc++} option
@cindex @option{effc++} warning option
This option warns about C++ code which breaks some of the programming
guidelines given in the books ``@cite{Effective C++}'' and ``@cite{More
Effective C++}'' by Scott Meyers. For example, a warning will be given
if a class which uses dynamically allocated memory does not define a
copy constructor and an assignment operator. Note that the standard
library header files do not follow these guidelines, so you may wish to
use this option as an occasional test for possible problems in your own
code rather than compiling with it all the time.
@item @option{-Wold-style-cast}
@cindex @option{-Wold-style-cast} option
@cindex @option{Wold-style-cast} option
@cindex @option{old-style-cast} warning option
This option highlights any uses of C-style casts in C++ programs. The
C++ language provides the keywords @code{static_cast}, @code{dynamic_cast},
@code{reinterpret_cast} and @code{const_cast} for handling casts
and these are often preferable (although C-style casts are still allowed).
@end table
@node Using the C++ standard library
@section Using the C++ standard library
@cindex C++, standard library
@cindex standard library, C++
@cindex library, C++ standard library
An implementation of the C++ standard library is provided as a part of
GCC. The following program uses the standard library @code{string}
class to reimplement the @dfn{Hello World} program:
@example
@verbatiminclude hellostr.cc
@end example
@noindent
The program can be compiled and run using the same commands as above:
@example
$ g++ -Wall hellostr.cc
$ ./a.out
Hello, World!
@end example
@noindent
@cindex C++, namespace @code{std}
@cindex namespace @code{std} in C++
@cindex @code{std} namespace in C++
@cindex header file, without @code{.h} extension for C++
Note that in accordance with the C++ standard, the header files for the
C++ library itself do not use a file extension. The classes in the
library are also defined in the @code{std} namespace, so the directive
@code{using namespace std} is needed to access them, unless the prefix
@code{std::} is used throughout (as in the previous section).
@node Templates
@section Templates
@cindex templates, in C++
@cindex generic programming, in C++
@cindex C++, templates
Templates provide the ability to define C++ classes which support
@dfn{generic programming} techniques. Templates can be considered as a
powerful kind of macro facility. When a templated class or function is
used with a specific class or type, such as @code{float} or @code{int},
the corresponding template code is compiled with that type substituted
in the appropriate places.
@menu
* Using C++ standard library templates::
* Providing your own templates::
* Explicit template instantiation::
* The export keyword::
@end menu
@node Using C++ standard library templates
@subsection Using C++ standard library templates
@cindex Standard Template Library (STL)
@cindex C++, standard library templates
The C++ standard library @file{libstdc++} supplied with GCC provides a
wide range of generic container classes such as lists and queues, in
addition to generic algorithms such as sorting. These classes were
originally part of the Standard Template Library (STL), which was a
separate package, but are now included in the C++ standard library
itself.
The following program demonstrates the use of the template library by
creating a list of strings with the template @code{list<string>}:
@example
@verbatiminclude string.cc
@end example
@noindent
No special options are needed to use the template classes in the
standard library; the command-line options for compiling this program
are the same as before:
@example
$ g++ -Wall string.cc
$ ./a.out
List size = 2
@end example
@noindent
@cindex C++, standard library
@cindex @code{libstdc++}, C++ standard library
Note that the executables created by @code{g++} using the C++ standard
library will be linked to the shared library @file{libstdc++}, which is
supplied as part of the default GCC installation. There are several
versions of this library---if you distribute executables using the C++
standard library you need to ensure that the recipient has a compatible
version of @file{libstdc++}, or link your program statically using the
command-line option @option{-static}.
@node Providing your own templates
@subsection Providing your own templates
@cindex instantiation, of templates in C++
@cindex C++, instantiation of templates
@cindex inclusion compilation model, in C++
@cindex compilation, model for templates
@cindex templates, inclusion compilation model
In addition to the template classes provided by the C++ standard library
you can define your own templates. The recommended way to use templates
with @code{g++} is to follow the @dfn{inclusion compilation model},
where template definitions are placed in header files. This is the
method used by the C++ standard library supplied with GCC itself. The
header files can then be included with @samp{#include} in each source
file where they are needed.
@cindex circular buffer, template example
@cindex buffer, template example
For example, the following template file creates a simple
@code{Buffer<T>} class which represents a circular buffer holding
objects of type @code{T}.
@example
@verbatiminclude buffer.h
@end example
@noindent
@cindex include guards, in header file
@cindex header file, with include guards
The file contains both the declaration of the class and the definitions
of the member functions. This class is only given for demonstration
purposes and should not be considered an example of good programming.
Note the use of @dfn{include guards}, which test for the presence of the
macro @w{@code{BUFFER_H}}, ensuring that the definitions in the header
file are only parsed once if the file is included multiple times in the
same context.
The program below uses the templated @code{Buffer} class to create a
buffer of size 10, storing the floating point values @math{0.25} and
@math{1.0} in the buffer:
@example
@verbatiminclude tprog.cc
@end example
@noindent
The definitions for the template class and its functions are included in
the source file for the program with @samp{#include "buffer.h"} before
they are used. The program can then be compiled using the following
command line:
@example
$ g++ -Wall tprog.cc
$ ./a.out
stored value = 1.25
@end example
@noindent
At the points where the template functions are used in the source file,
@code{g++} compiles the appropriate definition from the header file and
places the compiled function in the corresponding object file.
@cindex multiply-defined symbol error, with C++
@cindex linker, GNU compared with other linkers
If a template function is used several times in a program it will be
stored in more than one object file. The GNU Linker ensures that only
one copy is placed in the final executable. Other linkers may report
``@dfn{multiply defined symbol}'' errors when they encounter more than
one copy of a template function---a method of working with these linkers
is described below.
@node Explicit template instantiation
@subsection Explicit template instantiation
@cindex templates, explicit instantiation
@cindex instantiation, explicit vs implicit in C++
@cindex explicit instantiation of templates
@cindex @option{-fno-implicit-templates} option, disable implicit instantiation
@cindex @option{fno-implicit-templates} option, disable implicit instantiation
To achieve complete control over the compilation of templates with
@code{g++} it is possible to require explicit instantiation of each
occurrence of a template, using the option
@option{-fno-implicit-templates}. This method is not needed when
using the GNU Linker---it is an alternative provided for systems with
linkers which cannot eliminate duplicate definitions of template
functions in object files.
In this approach, template functions are no longer compiled at the point
where they are used, as a result of the @option{-fno-implicit-templates}
option. Instead, the compiler looks for an explicit instantiation of
the template using the @code{template} keyword with a specific type to
force its compilation (this is a GNU extension to the standard
behavior). These instantiations are typically placed in a separate
source file, which is then compiled to make an object file containing
all the template functions required by a program. This ensures that
each template appears in only one object file, and is compatible with
linkers which cannot eliminate duplicate definitions in object files.
For example, the following file @file{templates.cc} contains an explicit
instantiation of the @code{Buffer<float>} class used by the program
@file{tprog.cc} given above:
@example
@verbatiminclude templates.cc
@end example
@noindent
The whole program can be compiled and linked using explicit
instantiation with the following commands:
@example
$ g++ -Wall -fno-implicit-templates -c tprog.cc
$ g++ -Wall -fno-implicit-templates -c templates.cc
$ g++ tprog.o templates.o
$ ./a.out
stored value = 1.25
@end example
@noindent
The object code for all the template functions is contained in the file
@file{templates.o}. There is no object code for template functions in
@file{tprog.o} when it is compiled with the @option{-fno-implicit-templates}
option.
If the program is modified to use additional types, then further
explicit instantiations can be added to the file @file{templates.cc}.
For example, the following code adds instantiations for Buffer objects
containing @code{double} and @code{int} values:
@example
@verbatiminclude templates2.cc
@end example
@noindent
@cindex C++, creating libraries with explicit instantiation
@cindex libraries, creating with explicit instantiation in C++
The disadvantage of explicit instantiation is that it is necessary to
know which template types are needed by the program. For a complicated
program this may be difficult to determine in advance. Any missing
template instantiations can be determined at link time, however, and
added to the list of explicit instantiations, by noting which functions
are undefined.
Explicit instantiation can also be used to make libraries of precompiled
template functions, by creating an object file containing all the
required instantiations of a template function (as in the file
@file{templates.cc} above). For example, the object file created from
the template instantiations above contains the machine code needed for
Buffer classes with @samp{float}, @samp{double} and @samp{int} types,
and could be distributed in a library.
@node The export keyword
@subsection The @code{export} keyword
@cindex @code{export} keyword, not supported in GCC
@cindex templates, @code{export} keyword
At the time of writing, GCC does not support the new C++ @code{export}
keyword (GCC 3.4.4).
This keyword was proposed as a way of separating the interface of
templates from their implementation. However it adds its own complexity
to the linking process, which can detract from any advantages in
practice.
The @code{export} keyword is not widely used, and most other compilers
do not support it either. The inclusion compilation model described
earlier is recommended as the simplest and most portable way to use
templates.
@node Security enhancement options
@chapter Security enhancement options
@cindex security enhancement options
@cindex options, security enhancement
Recent GCC (4.1 or newer) on modern hardwares provides a good range of
security enhancement options. Popular security enhancement options used by
the major Linux distributions for their package building defaults and some
non-default options are described here.@footnote{For Debian wheezy, you can
obtain distribution recommended GCC options using the @code{dpkg-buildflag}
command.} You should consider enabling these options for your application as
needed by explicitly specifying them.
Please note that these security enhancement options may not be available on
your platform.
Please also note that these security enhancement options may cause problems
depending on your GCC version and your application. Since some distributions
make these options as the default of GCC, you may need to explicitly disable
these options for some limited situations to avoid such problems.
@menu
* Warning for format string::
* Stack smashing protector (SSP)::
* Buffer overflow protection::
* Read-only relocations::
* Binding policy NOW::
@end menu
@node Warning for format string
@section Warning for format string
@cindex warning for format string
@cindex @option{-Wformat-security} option, warn about uncontrolled format string
@cindex @option{-Wformat} option, warn about incorrect format strings
@cindex uncontrolled format string
The possible security vulnerability of uncontrolled format
string@footnote{@uref{http://en.wikipedia.org/wiki/Uncontrolled_format_string}}
in @code{printf()} and the similar functions can be detected and warned with GCC using the
option @option{-Wformat -Wformat-security}.
Example of insecure code: @file{format.c}
@example
@verbatiminclude format.c
@end example
@noindent
The insecure program @file{format.c} can be compiled without obvious warnings.
@example
$ gcc -Wall format.c
@end example
@noindent
The insecure program @file{format.c} can be compiled with the option
@option{-Wformat -Wformat-security} with warnings.
@example
$ gcc -Wformat -Wformat-security format.c
format.c: In function ‘main’:
format.c:9:7: warning: format not a string literal and no format arguments
[-Wformat-security]
@end example
@noindent
The output shows that the @file{format.c} program compiled with the option
@option{-Wformat-security} warns about the possible security vulnerability of
uncontrolled format string.
@node Stack smashing protector (SSP)
@section Stack smashing protector (SSP)
@cindex stack smashing protector
@cindex SSP, stack smashing protector
@cindex @option{-fstack-protector} option
@cindex @option{--param=ssp-buffer-size=4} option
Exploitability of many buffer
overflows@footnote{@uref{http://en.wikipedia.org/wiki/Buffer_overflow_protection}}
can be mitigated by compiling a program with GCC using the option
@option{-fstack-protector}.@footnote{You may use the option
@option{-fstack-protector --param=ssp-buffer-size=4} instead to protect more
functions with SSP. See @file{/usr/share/doc/gcc-*/README.ssp}.}
This option causes the GCC to insert a check for stack buffer overflows before
function returns. If an attempt is made to exploit a buffer overflow
vulnerability in the program, the application will be killed immediately. This
reduces the risk of any unknown potential exploits to a denial-of-service.
Example of insecure code: @file{bof.c}
@example
@verbatiminclude bof.c
@end example
@noindent
The insecure program @file{bof.c} can be compiled without obvious warnings.
@example
$ gcc -Wall bof.c -o bof
$ ./bof '123456789' || echo error
>>> Before the possible buffer over flow >>>
<<< After the possible buffer over flow <<<
@end example
@noindent
The output shows that the @file{bof.c} program compiled without using
the option @option{-fstack-protector} creates an executable @file{bof} which
executes an insecure buffer overflow code silently.
The insecure program @file{bof.c} can be compiled with the option
@option{-fstack-protector}.
@example
$ gcc -Wall -fstack-protector bof.c -o bof-ssp
$ ./bof-ssp '123456789' || echo error
>>> Before the possible buffer over flow >>>
<<< After the possible buffer over flow <<<
*** stack smashing detected ***: ./bof-ssp terminated
... [snipped]
Aborted
Error
@end example
@noindent
The output shows that the @file{bof.c} program compiled with the option
@option{-fstack-protector} creates an executable @file{bof-ssp}. When the
executable @file{bof-ssp} is executed, it detects stack smashing and exits safely.
@node Buffer overflow protection
@section Buffer overflow protection
@cindex buffer overflow protection
@cindex @option{-D_FORTIFY_SOURCE} option
@cindex @option{-O1} option, optimization level one
@cindex @option{-O2} option, optimization level two
@cindex @code{_FORTIFY_SOURCE} macro
The GCC macro definition of @option{-D_FORTIFY_SOURCE} provides a lightweight
buffer overflow protection to some memory and string functions provided by the
GLIBC. This feature uses macro substitution of such vulnerable functions to
prevent an insecure buffer overflow code to be executed. The compiler
optimization option needs to be @option{-O1} or higher to enable
@option{-D_FORTIFY_SOURCE}.@footnote{@uref{http://www.redhat.com/archives/fedora-tools-list/2004-September/msg00002.html}}
The insecure program @file{bof.c} shown in the previous section can be compiled
with the option @option{-D_FORTIFY_SOURCE=2 -O2}.
@example
$ gcc -Wall -D_FORTIFY_SOURCE=2 -O2 bof.c -o bof-fort
$ ./bof-fort '123456789' || echo error
>>> Before the possible buffer over flow >>>
*** buffer overflow detected ***: ./bof-fort terminated
... [snipped]
Aborted
Error
@end example
@noindent
The output shows that the @file{bof.c} program compiled with the option
@option{-D_FORTIFY_SOURCE=2 -O2} creates an executable @file{bof-fort} which
stops before executing an insecure buffer overflow code.
This @option{-D_FORTIFY_SOURCE} option is a quick fix for older programs
written with fixed length buffers. But if you are writing a software program
from scratch, please consider to use the secure libraries such as the
@code{GLib} library@footnote{@uref{http://en.wikipedia.org/wiki/GLib}} instead
of the standard @code{Libc} library.
@node Read-only relocations
@section Read-only relocations
@cindex Read-only relocations
@cindex @option{-Wl,z,relro} option
The GCC linker option of @option{-Wl,z,relro} for the read-only relocations provides
read-only protection to several ELF memory sections after the program is loaded
and linked completely by the linker to prevent attacks that involve overwriting
data in the Global Offset Table (GOT).
@node Binding policy NOW
@section Binding policy NOW
@cindex Binding policy NOW
@cindex @option{-Wl,z,now} option
@cindex @option{-Wl,z,relro} option
The GCC optional linker option of @option{-Wl,z,now} for the binding policy NOW
forces the program to load and link completely and marks its GOT read-only with
the @option{-Wl,z,relro} option before turning over control to the program.
Since this option causes start-up slowdown for large applications, this is not
enabled by default. But this option may be interesting for the security
conscious network daemons.
@node Platform-specific options
@chapter Platform-specific options
@cindex platform-specific options
@cindex machine-specific options
@cindex options, platform-specific
@cindex @option{-m} option, platform-specific settings
@cindex @option{m} option, platform-specific settings
GCC provides a range of platform-specific options for different types of
CPUs. These options control features such as hardware floating-point
modes, and the use of special instructions for different CPUs. They can
be selected with the @option{-m} option on the command line, and work
with all the GCC language frontends, such as @code{gcc} and @code{g++}.
The following sections describe some of the options available for common
platforms. A complete list of all platform-specific options can be
found in the GCC Reference Manual, ``@cite{Using GCC}'' (@pxref{Further
reading}). Support for new processors is added to GCC as they become
available, therefore some of the options described in this chapter may
not be found in older versions of GCC.
@menu
* Intel and AMD x86 options::
* DEC Alpha options::
* SPARC options::
* POWER/PowerPC options::
* Multi-architecture support::
* Floating-point issues::
* Portability of signed and unsigned types::
@end menu
@node Intel and AMD x86 options
@section Intel and AMD x86 options
@cindex Intel x86, platform-specific options
@cindex AMD x86, platform-specific options
@cindex x86, platform-specific options
The features of the widely used Intel and AMD x86 families of processors
(386, 486, Pentium, etc) can be controlled with GCC platform-specific
options.
On these platforms, GCC produces executable code which is compatible with
all the processors in the x86 family by default---going all the way back
to the 386. However, it is also possible to compile for a specific
processor to obtain better performance.@footnote{Also referred to as
``targeting'' a specific processor.}
@cindex Pentium, platform-specific options
@cindex Athlon, platform-specific options
For example, recent versions of GCC have specific support for newer
processors such as the Pentium 4 and AMD Athlon. These can be selected
with the following option for the Pentium 4,
@example
$ gcc -Wall -march=pentium4 hello.c
@end example
@noindent
@cindex @option{-march} option, compile for specific CPU
@cindex @option{march} option, compile for specific CPU
and for the Athlon:
@example
$ gcc -Wall -march=athlon hello.c
@end example
@noindent
A complete list of supported CPU types can be found in the GCC Reference
Manual.
Code produced with a specific @option{-march=@var{CPU}} option will be
faster but will not run on other processors in the x86 family. If you
plan to distribute executable files for general use on Intel and AMD
processors they should be compiled without any @option{-march} options.
@cindex @option{-mtune} option
@cindex @option{mtune} option
@cindex @option{tune} machine-specific option
As an alternative, the @option{-mcpu=@var{CPU}} option provides a
compromise between speed and portability---it generates code that is
tuned for a specific processor, in terms of instruction scheduling, but
does not use any instructions which are not available on other CPUs in
the x86 family.@footnote{In recent versions of GCC this option has been
renamed to @option{-mtune}. The older form @option{-mcpu} will continue
to work.} The resulting code will be compatible with all the CPUs, and
have a speed advantage on the CPU specified by @option{-mcpu}. The
executables generated by @option{-mcpu} cannot achieve the same
performance as @option{-march}, but may be more convenient in practice.
@menu
* x86 extensions::
* x86 64-bit processors ::
@end menu
@node x86 extensions
@subsection x86 extensions
@cindex SSE extensions
@cindex MMX extensions
@cindex illegal instruction error
@cindex @option{-msse} and related options
@cindex @option{msse} and related options
GCC can take advantage of the additional instructions in the MMX, SSE,
SSE2, SSE3 and 3dnow extensions of recent Intel and AMD processors. The
options @option{-mmmx}, @option{-msse}, @option{-msse2}, @option{-msse3}
and @option{-m3dnow} enable the use of these extra instructions, allowing
multiple words of data to be processed in parallel. The resulting
executables will only run on processors supporting the appropriate
extensions---on other systems they will crash with an @code{Illegal
instruction} error (or similar).@footnote{On GNU/Linux systems, the command @code{cat /proc/cpuinfo} will display information about the CPU.}
@cindex floating point arithmetic, with SSE extensions
@cindex @option{-mfpmath} option, for floating-point arithmetic
@cindex @option{mfpmath} option, for floating-point arithmetic
@cindex @option{fpmath} option, for floating-point arithmetic
The option @option{-mfpmath=sse} instructs GCC to use the SSE extensions
for floating-point arithmetic where possible. For this option to take
effect, the SSE or SSE2 extensions must first be enabled with
@option{-msse} or @option{-msse2}.
Note that the plain SSE extensions only support single precision
operations---double precision arithmetic is part of SSE2. Since most C
and C++ programs declare floating-point variables as @code{double}
rather than @code{float}, the combined options @code{-msse2
-mfpmath=sse} are usually needed. On 64-bit processors these
options are enabled by default.
@node x86 64-bit processors
@subsection x86 64-bit processors
@cindex 64-bit processor-specific options, AMD64 and Intel
@cindex AMD64, 64-bit processor specific options
AMD has enhanced the 32-bit x86 instruction set to a 64-bit instruction
set called x86-64, which is implemented in their AMD64
processors.@footnote{Intel has added support for this instruction set as
the ``Intel 64-bit enhancements'' on their Xeon CPUs.} On AMD64 systems
GCC generates 64-bit code by default. The option @option{-m32} allows
32-bit code to be generated instead.
@cindex @option{-mcmodel} option, for AMD64
@cindex @option{mcmodel} option, for AMD64
The AMD64 processor has several different memory models for programs
running in 64-bit mode. The default model is the small code model,
which allows code and data up to 2@dmn{GB} in size. The medium code
model allows unlimited data sizes and can be selected with
@option{-mcmodel=medium}. There is also a large code model, which
supports an unlimited code size in addition to unlimited data size. It
is not currently implemented in GCC since the medium code model is
sufficient for all practical purposes---executables with sizes greater
than 2@dmn{GB} are not encountered in practice.
@cindex red-zone, on AMD64
@cindex kernel mode, on AMD64
A special kernel code model @option{-mcmodel=kernel} is provided for
system-level code, such as the Linux kernel. An important point to note
is that by default on the AMD64 there is a 128-byte area of memory
allocated below the stack pointer for temporary data, referred to as the
``red-zone'', which is not supported by the Linux kernel. Compilation
of the Linux kernel on the AMD64 requires the options
@option{-mcmodel=kernel -mno-red-zone}.
@node DEC Alpha options
@section DEC Alpha options
@cindex Alpha, platform-specific options
@cindex DEC Alpha, platform-specific options
The DEC Alpha processor has default settings which maximize
floating-point performance, at the expense of full support for IEEE
arithmetic features.
@cindex IEEE options, on DEC Alpha
@cindex @option{-mieee} option, floating-point support on DEC Alpha
@cindex @option{mieee} option, floating-point support on DEC Alpha
@cindex NaN, not a number, on DEC Alpha
@cindex Inf, infinity, on DEC Alpha
@cindex denormalized numbers, on DEC Alpha
@cindex underflow, on DEC Alpha
@cindex gradual underflow, on DEC Alpha
@cindex soft underflow, on DEC Alpha
@cindex zero, from underflow on DEC Alpha
Support for infinity arithmetic and gradual underflow (denormalized
numbers) is not enabled in the default configuration on the DEC Alpha
processor. Operations which produce infinities or underflows will
generate floating-point exceptions (also known as @dfn{traps}), and
cause the program to terminate, unless the operating system catches and
handles the exceptions (which is, in general, inefficient). The IEEE
standard specifies that these operations should produce special results
to represent the quantities in the IEEE numeric format.
In most cases the DEC Alpha default behavior is acceptable, since the
majority of programs do not produce infinities or underflows. For
applications which require these features, GCC provides the option
@option{-mieee} to enable full support for IEEE arithmetic.
To demonstrate the difference between the two cases the following
program divides 1 by 0:
@cindex division by zero
@cindex zero, division by
@example
@verbatiminclude alpha.c
@end example
@noindent
In IEEE arithmetic the result of 1/0 is @code{inf} (@dfn{Infinity}).
If the program is compiled for the Alpha processor with the default settings
it generates an exception, which terminates the program:
@example
$ gcc -Wall alpha.c
$ ./a.out
Floating point exception @r{(on an Alpha processor)}
@end example
@noindent
@cindex floating point exception, on DEC Alpha
Using the @option{-mieee} option ensures full IEEE compliance -- the
division 1/0 correctly produces the result @code{inf} and the program
continues executing successfully:
@example
$ gcc -Wall -mieee alpha.c
$ ./a.out
x/y = inf
@end example
@noindent
Note that programs which generate floating-point exceptions run more
slowly when compiled with @option{-mieee}, because the exceptions are
handled in software rather than hardware.
@node SPARC options
@section SPARC options
@cindex Sun SPARC, platform-specific options
@cindex SPARC, platform-specific options
@cindex @option{-mcpu} option, compile for specific CPU
@cindex @option{mcpu} option, compile for specific CPU
On the SPARC range of processors the @option{-mcpu=@var{CPU}} option
generates processor-specific code. The valid options for
@code{@var{CPU}} are @code{v7}, @code{v8} (SuperSPARC),
@code{Sparclite}, @code{Sparclet} and @code{v9} (UltraSPARC). Code
produced with a specific @option{-mcpu} option will not run on other
processors in the SPARC family, except where supported by the
backwards-compatibility of the processor itself.
@cindex UltraSPARC, 32-bit mode vs 64-bit mode,
@cindex word-size, on UltraSPARC
@cindex bits, 32 vs 64 on UltraSPARC
@cindex @option{-m32} and @option{-m64} options, compile for 32 or 64-bit environment
@cindex @option{m32} and @option{m64} options, compile for 32 or 64-bit environment
On 64-bit UltraSPARC systems the options @option{-m32} and @option{-m64}
control code generation for 32-bit or 64-bit environments. The 32-bit
environment selected by @option{-m32} uses @code{int}, @code{long} and
pointer types with a size of 32 bits. The 64-bit environment selected by
@option{-m64} uses a 32-bit @code{int} type and 64-bit @code{long} and
pointer types.
@node POWER/PowerPC options
@section POWER/PowerPC options
@cindex PowerPC and POWER, platform-specific options
@cindex AIX, platform-specific options
On systems using the POWER/PowerPC family of processors the option
@option{-mcpu=@var{CPU}} selects code generation for specific CPU
models. The possible values of @code{@var{CPU}} include @samp{power},
@samp{power2}, @samp{powerpc}, @samp{powerpc64} and @samp{common}, in
addition to other more specific model numbers. Code generated with
the option @option{-mcpu=common} will run on any of the processors.
@cindex Altivec, on PowerPC
@cindex @option{-maltivec} option, enables use of Altivec processor on PowerPC
@cindex @option{maltivec} option, enables use of Altivec processor on PowerPC
The option @option{-maltivec} enables use of the Altivec vector
processing instructions, if the appropriate hardware support is
available.
@cindex multiply and add instruction
@cindex fused multiply and add instruction
@cindex combined multiply and add instruction
@cindex @option{-mno-fused-madd} option, on PowerPC
@cindex @option{mno-fused-madd} option, on PowerPC
The POWER/PowerPC processors include a combined ``multiply and add''
instruction @math{a * x + b}, which performs the two operations
simultaneously for speed---this is referred to as a @dfn{fused} multiply
and add, and is used by GCC by default. Due to differences in the way
intermediate values are rounded, the result of a fused instruction may
not be exactly the same as performing the two operations separately. In
cases where strict IEEE arithmetic is required, the use of the combined
instructions can be disabled with the option @option{-mno-fused-madd}.
@cindex TOC overflow error, on AIX
@cindex table of contents, overflow error on AIX
@cindex overflow error, for TOC on AIX
@cindex AIX, TOC overflow error
@cindex @option{-mminimal-toc} option, on AIX
@cindex @option{mminimal-toc} option, on AIX
On AIX systems, the option @option{-mminimal-toc} decreases the number
of entries GCC puts in the global @dfn{table of contents} (TOC) in
executables, to avoid ``TOC overflow'' errors at link time.
@cindex @option{-mxl-call} option, compatibility with IBM XL compilers on AIX
@cindex @option{mxl-call} option, compatibility with IBM XL compilers on AIX
@cindex IBM XL compilers, compatibility on AIX
@cindex XL compilers, compatibility on AIX
@cindex AIX, compatibility with IBM XL compilers
The option @option{-mxl-call} makes the linking of object files from GCC
compatible with those from IBM's XL compilers.
@cindex @option{-pthread} option, on AIX
@cindex @option{pthread} option, on AIX
@cindex threads, on AIX
For applications using POSIX threads, AIX always requires the option
@option{-pthread} when compiling, even when the program will only run in
single-threaded mode.
@node Multi-architecture support
@section Multi-architecture support
@cindex multi-architecture support, discussion of
@cindex MIPS64, multi-architecture support
@cindex Sparc64, multi-architecture support
@cindex PowerPC64, multi-architecture support
@cindex ARM, multi-architecture support
@cindex Thumb, alternative code format on ARM
A number of platforms can execute code for more than one architecture.
For example, 64-bit platforms such as AMD64, MIPS64, Sparc64, and
PowerPC64 support the execution of both 32-bit and 64-bit code.
Similarly, ARM processors support both ARM code and a more compact code
called ``Thumb''. GCC can be built to support multiple architectures on
these platforms. By default, the compiler will generate 64-bit object
files, but giving the @option{-m32} option will generate a 32-bit object
file for the corresponding architecture.@footnote{The options
@option{-maix64} and @option{-maix32} are used on AIX.}
@cindex system libraries, location of
Note that support for multiple architectures depends on the
corresponding libraries being available. GCC knows about these paths
and uses the appropriate path when compiling 64-bit or 32-bit code.
@cindex multi-architecture support, Debian
@cindex multi-architecture support, Ubuntu
On systems simultaneously supporting multiple binary target
architectures such as Debian wheezy and Ubuntu 11.04, the libraries with
the corresponding architecture ABI will be stored in
@file{/usr/lib/@var{multiarch_name}} and
@file{/lib/@var{multiarch_name}}. The multiarch architecture specifier
(tuple) @file{@var{multiarch_name}} takes values such as
@file{x86_64-linux-gnu} for the 64-bit PC Linux versions, and
@file{i386-linux-gnu} for the 32-bit PC Linux versions. Please note
that the multiarch architecture specifier is not exactly the same as the
GNU triplets although they are similar.
@cindex multi-architecture support, RedHat
@cindex multi-architecture support, older systems
@cindex Itanium, multi-architecture support
On most system simultaneously supporting only 32-bit and 64-bit binary
target architectures such as RedHat, the 64-bit versions of the
libraries will often be stored in @file{/usr/lib64} and @file{/lib64},
with the 32-bit versions in @file{/usr/lib} and @file{/lib}. Other
systems, such as the IA64/Itanium, use the directories @file{/usr/lib}
and @file{/lib} for 64-bit libraries.
@node Floating-point issues
@section Floating-point issues
@cindex floating point, portability problems
@cindex arithmetic, floating-point
@cindex numerical differences
@macro scinum{a,b}
@iftex
@tex
$\a\ \\times 10^{ \b\ }$@comment
@end tex
@end iftex
@ifnottex
\a\*10^\b\@comment
@end ifnottex
@end macro
@macro sciexp{a,b}
@iftex
@tex
$\a\^{ \b\ }$@comment
@end tex
@end iftex
@ifnottex
\a\^\b\@comment
@end ifnottex
@end macro
@macro scirange{a,b}
@iftex
@tex
$\a\^{\\pm \b\ }$@comment
@end tex
@end iftex
@ifnottex
\a\^(+/-\b\)@comment
@end ifnottex
@end macro
@cindex IEEE arithmetic
The IEEE-754 standard defines the bit-level behavior of floating-point
arithmetic operations on all modern processors. This allows numerical
programs to be ported between different platforms with identical
results, in principle. In practice, there are often minor variations
caused by differences in the order of operations (depending on the
compiler and optimization level) but these are generally not
significant.
@cindex x86, floating-point arithmetic
@cindex Motorola 680x0, floating-point arithmetic
@cindex native double-precision processors
@cindex double precision
@cindex extended precision, x86 processors
However, more noticeable discrepancies can be seen when porting
numerical programs between x86 systems and other platforms, because the
the x87 floating point unit (FPU) on x86 processors computes results
using extended precision internally (the values being converted to
double precision only when they are stored to memory). In contrast,
processors such as SPARC, PA-RISC, Alpha, MIPS and POWER/PowerPC work
with native double-precision values throughout.@footnote{Motorola 68k
processors also use extended precision registers, like the x86.} The
differences between these implementations lead to changes in rounding
and underflow/overflow behavior, because intermediate values have a
greater relative precision and exponent range when computed in extended
precision.@footnote{For quantities held in the x87 extended-precision
registers the relative precision is
@scinum{5.42,-20}
and the exponent
range is
@scirange{10,4932}@c
. Standard double precision values have a
relative precision of
@scinum{2.22,-16}
and an exponent range of
@scirange{10,308}@c
.} In particular, comparisons involving extended
precision values may fail where the equivalent double precision values
would compare equal.
@cindex rounding, floating-point arithmetic
@cindex overflow, floating-point arithmetic
@cindex underflow, floating-point arithmetic
To avoid these incompatibilities, the x87 FPU also offers a hardware
double-precision rounding mode. In this mode the results of each
extended-precision floating-point operation are rounded to
double precision in the floating-point registers by the FPU.
It is important to note that the rounding
only affects the precision, not the exponent range, so the result is a
hybrid double-precision format with an extended range of exponents.
@cindex FreeBSD, floating-point arithmetic
@cindex NetBSD, floating-point arithmetic
@cindex OpenBSD, floating-point arithmetic
@cindex GNU/Linux, floating-point arithmetic
@cindex Linux kernel, floating-point
@cindex @code{fldcw} set floating point mode
@cindex @code{asm} extension keyword
@cindex machine instruction, @code{asm} keyword
On BSD systems such as FreeBSD, NetBSD and OpenBSD, the hardware
double-precision rounding mode is the default, giving the greatest
compatibility with native double precision platforms. On x86 GNU/Linux
systems the default mode is extended precision (with the aim of
providing increased accuracy). To enable the double-precision rounding
mode it is necessary to override the default setting on per-process
basis using the @sc{fldcw} ``floating-point load control-word'' machine
instruction.@footnote{The operating system saves and restores the
control word when switching between processes, so that each process
maintains its own setting.} A simple function which can be called to
execute this instruction is shown below. It uses the GCC extension
keyword @code{asm} to insert the specified instruction in the
assembly language output:
@example
@verbatiminclude setfpu.c
@end example
@noindent
The appropriate @code{mode} setting for double-precision rounding is
@code{0x27F}. The mode value also controls the floating-point exception
handling behavior and rounding-direction (see the Intel and AMD
processor reference manuals for details).
@cindex floating point exception handling
@cindex exception handling, floating-point
On x86 GNU/Linux, the function above can be called at the start of any
program to disable excess precision. This will then reproduce the
results of native double-precision processors, in the absence of
underflows and overflows.
The following program demonstrates the different rounding modes:
@example
@verbatiminclude fptest2.c
@end example
@noindent
On x86 GNU/Linux systems the comparison @code{c == a / b} can produce an
unexpected result if @code{c} is taken from memory (double precision)
while @code{a / b} is computed in extended precision, because the
fraction 3/7 has different representations in double and extended
precision.
@example
$ gcc -Wall fptest.c
$ ./a.out
unexpected result
@end example
@noindent
Setting the hardware rounding mode to double precision prevents this
from happening:
@example
$ gcc -Wall -DDOUBLE fptest.c
$ ./a.out
comparison succeeds
@end example
@noindent
Note that the floating-point control word affects the whole environment
of the process, including any C Library functions that are called. One
consequence of this is that @code{long double} arithmetic is effectively
reduced to double precision, since it relies on extended precision operations.
@cindex long double arithmetic
@c @cindex @option{-ffloat-store}
@c The option @option{-ffloat-store} is sometimes suggested as a way to
@c avoid problems with excess precision---it forces floating-point values
@c to be stored in memory when they are assigned to a variable. However,
@c it does not affect intermediate expressions or conditionals, and can
@c slow down programs significantly. If necessary, it is possible to force
@c a single variable to remain in memory is by declaring it
@c @code{volatile}.
@c @example
@c @verbatiminclude coerce.h
@c @end example
@c @noindent
@c @example
@c @c @verbatiminclude fp.c
@c @end example
@c @noindent
@cindex SSE/SSE2 precision
The floating point control word only affects the behavior of the x87
FPU. Floating point operations computed with SSE and SSE2 instructions
are always carried out in native double precision. Thus, the combined
options
@example
$ gcc -Wall -msse2 -mfpmath=sse ...
@end example
@noindent
are often sufficient to remove the effects of extended-precision.
However, some operations (such as transcendental functions) are not
available in the SSE/SSE2 extensions and will still be computed on the
x87 FPU.
@node Portability of signed and unsigned types
@section Portability of signed and unsigned types
@cindex signed @code{char} option
@cindex unsigned @code{char} option
@cindex @code{char}, portability of signed vs unsigned
The C and C++ standards allows the character type @code{char} to be
signed or unsigned, depending on the platform and compiler. Most
systems, including x86 GNU/Linux and Microsoft Windows, use signed
@code{char}, but those based on PowerPC and @sc{arm} processors
typically use unsigned @code{char}.@footnote{MacOS X (Darwin) on
PowerPC uses signed @code{char}, for consistency with other Darwin
architectures.} This can lead to unexpected results when porting
programs between platforms which have different defaults for the type
of @code{char}.
The following code demonstrates the difference between platforms with
signed and unsigned @code{char} types:
@example
@verbatiminclude signed.c
@end example
@noindent
With an unsigned @code{char}, the variable @code{c} takes the value 255,
but with a signed @code{char} it becomes @math{-1}.
The correct way to manipulate @code{char} variables in C is through the
portable functions declared in @file{ctype.h}, such as @code{isalpha},
@code{isdigit} and @code{isblank}, rather than by their numerical
values. The behavior of non-portable conditional expressions such as
@code{c > 'a'} depends on the signedness of the @code{char} type. If
the signed or unsigned version of @code{char} is explicitly required at
certain points in a program, it can be specified using the declarations
@code{signed char} or @code{unsigned char}.
For existing programs which assume that @code{char} is signed or
unsigned, GCC provides the options @option{-fsigned-char} and
@option{-funsigned-char} to set the default type of @code{char}. Using
these options, the example code above compiles cleanly when @code{char}
is unsigned:
@cindex @option{-funsigned-char} option
@cindex @option{-fsigned-char} option
@example
$ gcc -Wall -funsigned-char signed.c
$ ./a.out
char is unsigned (c = 255)
@end example
@noindent
However, when @code{char} is signed the value 255 wraps around to
@math{-1}, giving a warning:
@example
$ gcc -Wall -fsigned-char signed.c
signed.c: In function `main':
signed.c:7: warning: comparison is always false due to
limited range of data type
$ ./a.out
char is signed (c = -1)
@end example
@noindent
The warning message @cite{``comparison is always true/false due to
limited range of data type''} is one symptom of code which assumes a
definition of @code{char} which is different from the actual type.
The most common problem with code written assuming signed @code{char}
types occurs with the functions @code{getc}, @code{fgetc} and
@code{getchar} (which read a character from a file). They have a return
type of @code{int}, not @code{char}, and this allows them to use the
special value @math{-1} (defined as @code{EOF}) to indicate an
end-of-file error. Unfortunately, many programs have been written which
incorrectly store this return value straight into a @code{char}
variable. Here is a typical example:
@example
@verbatiminclude testgetc.c
@end example
@noindent
This only works on platforms which default to a signed @code{char}
type.@footnote{There is also a subtle error even on
platforms with signed @code{char}---the @sc{ascii} character 255
is spuriously interpreted as an end of file condition.}
On platforms which use an unsigned @code{char} the same code will fail,
because the value @math{-1} becomes 255 when stored in an @code{unsigned
char}. This usually causes an infinite loop because the end of the file
cannot be recognized.@footnote{If displayed, character code 255 often appears as @code{@"y}.}
To be portable, the program should test the
return value as an integer before coercing it to a @code{char}, as
follows:
@example
@verbatiminclude testgetc2.c
@end example
@noindent
@cindex signed bitfield option
@cindex unsigned bitfield option
@cindex bitfields, portability of signed vs unsigned
@cindex @option{-funsigned-bitfields} option
@cindex @option{-fsigned-bitfields} option
The same considerations described in this section apply to the
definitions of bitfields in structs, which can be signed or unsigned by
default. In GCC, the default type of bitfields can be controlled using
the options @option{-fsigned-bitfields} and @option{-funsigned-bitfields}.
@node Troubleshooting
@chapter Troubleshooting
@cindex troubleshooting options
@cindex help options
@cindex command-line help option
GCC provides several help and diagnostic options to assist in
troubleshooting problems with the compilation process. All the options
described in this chapter work with both @code{gcc} and @code{g++}.
@menu
* Help for command-line options::
* Version numbers::
* Verbose compilation::
* Stopping a program in an infinite loop::
* Preventing excessive memory usage::
@end menu
@node Help for command-line options
@section Help for command-line options
@cindex @option{--help} option, display command-line options
To obtain a brief reminder of various command-line options, GCC provides
a help option which displays a summary of the top-level GCC command-line
options:
@example
$ gcc --help
@end example
@noindent
@cindex verbose help option
@cindex @option{-v} option, verbose compilation
@cindex @option{v} option, verbose compilation
To display a complete list of options for @code{gcc} and its associated
programs, such as the GNU Linker and GNU Assembler, use the help option
above with the verbose (@option{-v}) option:
@example
$ gcc -v --help
@end example
@noindent
The complete list of options produced by this command is extremely
long---you may wish to page through it using the @code{more} command, or
redirect the output to a file for reference:
@example
$ gcc -v --help 2>&1 | more
@end example
@node Version numbers
@section Version numbers
You can find the version number of @code{gcc} using the version
option:
@cindex version number of GCC, displaying
@cindex @option{--version} option, display version number
@example
$ gcc --version
gcc (GCC) 3.3.1
@end example
@noindent
The version number is important when investigating compilation problems,
since older versions of GCC may be missing some features that a program
uses. The version number has the form @var{major-version.minor-version}
or @var{major-version.minor-version.micro-version}, where the additional
third ``micro'' version number (as shown above) is used for subsequent
bug-fix releases in a release series.
@cindex major version number, of GCC
@cindex minor version number, of GCC
@cindex patch level, of GCC
More details about the version can be found using @option{-v}:
@example
$ gcc -v
Reading specs from /usr/lib/gcc-lib/i686/3.3.1/specs
Configured with: ../configure --prefix=/usr
Thread model: posix
gcc version 3.3.1
@end example
@noindent
@cindex configuration files for GCC
@cindex @code{specs} directory, compiler configuration files
This includes information on the build flags of the compiler itself and
the installed configuration file, @file{specs}.
@node Verbose compilation
@section Verbose compilation
@cindex verbose compilation, @option{-v} option
The @option{-v} option can also be used to display detailed information
about the exact sequence of commands used to compile and link a program.
Here is an example which shows the verbose compilation of the
@cite{Hello World} program:
@example
$ gcc -v -Wall hello.c
Reading specs from /usr/lib/gcc-lib/i686/3.3.1/specs
Configured with: ../configure --prefix=/usr
Thread model: posix
gcc version 3.3.1
/usr/lib/gcc-lib/i686/3.3.1/cc1 -quiet -v -D__GNUC__=3
-D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=1
hello.c -quiet -dumpbase hello.c -auxbase hello -Wall
-version -o /tmp/cceCee26.s
GNU C version 3.3.1 (i686-pc-linux-gnu)
compiled by GNU C version 3.3.1 (i686-pc-linux-gnu)
GGC heuristics: --param ggc-min-expand=51
--param ggc-min-heapsize=40036
ignoring nonexistent directory "/usr/i686/include"
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/include
/usr/lib/gcc-lib/i686/3.3.1/include
/usr/include
End of search list.
as -V -Qy -o /tmp/ccQynbTm.o /tmp/cceCee26.s
GNU assembler version 2.12.90.0.1 (i386-linux)
using BFD version 2.12.90.0.1 20020307 Debian/GNU
Linux
/usr/lib/gcc-lib/i686/3.3.1/collect2
--eh-frame-hdr -m elf_i386 -dynamic-linker
/lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o
/usr/lib/gcc-lib/i686/3.3.1/crtbegin.o
-L/usr/lib/gcc-lib/i686/3.3.1
-L/usr/lib/gcc-lib/i686/3.3.1/../../.. /tmp/ccQynbTm.o
-lgcc -lgcc_eh -lc -lgcc -lgcc_eh
/usr/lib/gcc-lib/i686/3.3.1/crtend.o
/usr/lib/crtn.o
@end example
@noindent
The output produced by @option{-v} can be useful
whenever there is a problem with the compilation
process itself. It displays the full directory
paths used to search for header files and
libraries, the predefined preprocessor symbols,
and the object files and libraries used for
linking.
@node Stopping a program in an infinite loop
@section Stopping a program in an infinite loop
@cindex infinite loop, stopping
@cindex control-C, interrupt
@cindex SIGINT signal
@cindex @code{attach}, debug running program
A program which goes into an infinite loop or ``hangs'' can be difficult
to debug. On most systems a foreground process can be stopped by
hitting @kbd{Control-C}, which sends it an interrupt signal (@sc{sigint}).
However, this does not help in debugging the problem---the @sc{sigint}
signal terminates the process without producing a core dump. A more
sophisticated approach is to @dfn{attach} to the running process with
a debugger and inspect it interactively.
For example, here is a simple program with an infinite loop:
@example
@verbatiminclude loop.c
@end example
@noindent
In order to attach to the program and debug it, the code should be
compiled with the debugging option @option{-g}:
@example
$ gcc -Wall -g loop.c
$ ./a.out
@r{(program hangs)}
@end example
@noindent
@cindex process id, finding
Once the executable is running we need to find its process id
(@sc{pid}). This can be done from another session with the command
@code{ps x}:
@example
$ ps x
PID TTY STAT TIME COMMAND
... ..... . ....
891 pts/1 R 0:11 ./a.out
@end example
@noindent
In this case the process id is 891, and we can now attach to it with
@code{gdb}. The debugger should be started in the directory containing
the executable and its source code:@footnote{Alternatively, the
appropriate paths can be set up in @code{gdb} using the @code{file} and
@code{directory} commands.}
@example
$ gdb a.out
(gdb) attach 891
Attaching to program: a.out, process 891
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
0x080483d4 in main () at loop.c:5
5 while (1) @{ i++; @};
(gdb)
@end example
@noindent
The output shows the line that was about to execute at the point when
the debugger attached to the process. The attached program is paused but
still ``live''---it can be examined interactively and continued or
terminated (with the @code{kill} command) if necessary:
@example
(gdb) print i
$1 = 1213315528
(gdb) kill
Kill the program being debugged? (y or n) y
(gdb)
@end example
@noindent
@cindex SIGQUIT signal
If you want to stop a process immediately and create a core dump, the
shell command @code{kill -3 @var{pid}} (where @var{pid} is the process
id) will send it a @sc{sigquit} signal. The @sc{sigquit} signal does
trigger a core dump, unlike @sc{sigint}. Note that if core dumps were
disabled when the process was started, no core file will be produced
(@pxref{Examining core files}).
@node Preventing excessive memory usage
@section Preventing excessive memory usage
@cindex memory usage, limiting
@cindex virtual memory usage, limiting
@cindex @command{ulimit} command
Sometimes a programming error will cause a process to allocate huge
amounts of memory, consuming all the @sc{ram} on a system. To prevent
this, the GNU Bash command @command{ulimit -v @var{limit}} can be used
to restrict the amount of virtual memory available to each process. The
limit is measured in kilobytes and applies to new processes started in
the current shell. For example,
@example
$ ulimit -v 4096
@end example
@noindent
will limit subsequent processes to 4 megabytes of virtual memory
(4096k). By default the limit cannot be increased in the same session
once it has been applied, so it is best to start a separate shell for
reduced @code{ulimit} operations. Alternatively, you can set a
@dfn{soft limit} (which can be undone) with the options @option{-S -v}.
In addition to preventing run-away processes, limiting the amount of
memory a program is allowed to allocate also provides a way to test how
robustly @dfn{out of memory} conditions are handled. An artificially low
limit can be used to simulate running out of memory---a well-written
program should not crash in this case.
@c The following program tries to allocate 32 megabytes of memory using
@c @code{malloc}:
@c @example
@c @verbatiminclude outofmem.c
@c @end example
@c @noindent
@c Under normal circumstances, the program executes without problems:
@c @example
@c $ gcc -Wall outofmem.c
@c $ ./a.out
@c Allocating 32 megabytes... success
@c @end example
@c If we restrict the available virtual memory to 4 megabytes, the call to
@c @code{malloc} will fail:
@c @example
@c $ ulimit -v 4096
@c $ ./a.out
@c Allocating 32 megabytes... FAILED
@c @end example
The @command{ulimit} command supports other options including
@option{-p}, which restricts the number of child processes that can be
created, and @option{-t}, which places a limit on the number of @sc{cpu}
seconds that a process can run for. The complete list of settings can be
shown with the command @code{ulimit -a}. To display more information
about the @code{ulimit} command, type @code{help ulimit} at the Bash prompt.
@node Compiler-related tools
@chapter Compiler-related tools
@cindex compiler-related tools
@cindex tools, compiler-related
This chapter describes a number of tools which are
useful in combination with GCC. These include the
GNU archiver @code{ar}, for creating libraries,
and the GNU profiling and coverage testing programs,
@code{gprof} and @code{gcov}.
@menu
* Creating a library with the GNU archiver::
* Using the profiler gprof::
* Coverage testing with gcov::
@end menu
@node Creating a library with the GNU archiver
@section Creating a library with the GNU archiver
@cindex @code{ar}, GNU archiver
@cindex libraries, creating with @code{ar}
The GNU archiver @code{ar} combines a collection of object files into a
single archive file, also known as a @dfn{library}. An archive file is
simply a convenient way of distributing a large number of related object
files together (as described earlier in @ref{Linking with external libraries}).
To demonstrate the use of the GNU archiver we will create a small
library @file{libhello.a} containing two functions @code{hello} and
@code{bye}.
The first object file will be generated from the source code for the
@code{hello} function, in the file @file{hello_fn.c} seen earlier:
@example
@verbatiminclude hello_fn.c
@end example
@noindent
The second object file will be generated from the source file
@file{bye_fn.c}, which contains the new function @code{bye}:
@example
@verbatiminclude bye_fn.c
@end example
@noindent
Both functions use the header file @file{hello.h}, now with a prototype
for the function @code{bye()}:
@example
@verbatiminclude hello.h
@end example
@noindent
The source code can be compiled to the object files @file{hello_fn.o}
and @file{bye_fn.o} using the commands:
@example
$ gcc -Wall -c hello_fn.c
$ gcc -Wall -c bye_fn.c
@end example
@noindent
@cindex @option{cr} option, create/replace archive files
These object files can be combined into a static library using the
following command line:
@example
$ ar cr libhello.a hello_fn.o bye_fn.o
@end example
@noindent
The option @option{cr} stands for ``create and replace''.@footnote{Note
that @code{ar} does not require a prefix @samp{-} for its options.} If
the library does not exist, it is first created. If the library already
exists, any original files in it with the same names are replaced by the new
files specified on the command line. The first argument
@file{libhello.a} is the name of the library. The remaining arguments
are the names of the object files to be copied into the library.
@cindex @option{t} option, archive table of contents
@cindex table of contents, in @code{ar} archive
The archiver @code{ar} also provides a ``table of contents'' option
@option{t} to list the object files in an existing library:
@example
$ ar t libhello.a
hello_fn.o
bye_fn.o
@end example
@noindent
Note that when a library is distributed, the header files for the public
functions and variables it provides should also be made available, so
that the end-user can include them and obtain the correct prototypes.
We can now write a program using the functions in the newly created
library:
@example
@verbatiminclude main3.c
@end example
@noindent
This file can be compiled with the following command line, as described
in @ref{Linking with external libraries}, assuming the library
@file{libhello.a} is stored in the current directory:
@example
$ gcc -Wall main.c libhello.a -o hello
@end example
@noindent
The main program is linked against the object files found in the library
file @file{libhello.a} to produce the final executable.
The short-cut library linking option @option{-l} can also be used to
link the program, without needing to specify the full filename of the
library explicitly:
@example
$ gcc -Wall -L. main.c -lhello -o hello
@end example
@noindent
The option @option{-L.} is needed to add the current directory to the
library search path. The resulting executable can be run as usual:
@example
$ ./hello
Hello, everyone!
Goodbye!
@end example
@noindent
It displays the output from both the @code{hello} and @code{bye}
functions defined in the library.
@node Using the profiler gprof
@section Using the profiler @code{gprof}
@cindex profiling, with @code{gprof}
@cindex @code{gprof}, GNU Profiler
The GNU profiler @code{gprof} is a useful tool for measuring the
performance of a program---it records the number of calls to each
function and the amount of time spent there, on a per-function basis.
Functions which consume a large fraction of the run-time can be
identified easily from the output of @code{gprof}. Efforts to speed up
a program should concentrate first on those functions which dominate the
total run-time.
@cindex Collatz sequence
We will use @code{gprof} to examine the performance of a small numerical
program which computes the lengths of sequences occurring in the
unsolved @cite{Collatz conjecture} in mathematics.@footnote{American
Mathematical Monthly, Volume 92 (1985), 3--23} The Collatz conjecture
involves sequences defined by the rule:
@tex
$$
x_{n+1} \leftarrow \cases{ x_n / 2 & if $x_n$ is even\cr
3 x_n + 1 & if $x_n$ is odd\cr}
$$
@end tex
@ifinfo
@example
x_@{n+1@} <= x_@{n@} / 2 if x_@{n@} is even
3 x_@{n@} + 1 if x_@{n@} is odd
@end example
@end ifinfo
@noindent
The sequence is iterated from an initial value @math{x_0} until it
terminates with the value 1. According to the conjecture, all sequences
do terminate eventually---the program below displays the longest
sequences as @math{x_0} increases. The source file @file{collatz.c}
contains three functions: @code{main}, @code{nseq} and @code{step}:
@smallexample
@verbatiminclude collatz.c
@end smallexample
@noindent
@cindex @option{-pg} option, enable profiling
@cindex @option{pg} option, enable profiling
@cindex enable profiling, @option{-pg} option
To use profiling, the program must be compiled and linked with the
@option{-pg} profiling option:
@example
$ gcc -Wall -c -pg collatz.c
$ gcc -Wall -pg collatz.o
@end example
@noindent
@cindex instrumented executable, for profiling
This creates an @dfn{instrumented} executable which contains additional
instructions that record the time spent in each function.
If the program consists of more than one source file then the
@option{-pg} option should be used when compiling each source file, and
used again when linking the object files to create the final executable
(as shown above). Forgetting to link with the option @option{-pg} is a
common error, which prevents profiling from recording any useful
information.
The executable must be run to create the profiling data:
@example
$ ./a.out
@r{(normal program output is displayed)}
@end example
@noindent
@cindex @code{gmon.out}, data file for @code{gprof}
While running the instrumented executable, profiling data is silently
written to a file @file{gmon.out} in the current directory. It can be
analyzed with @code{gprof} by giving the name of the executable as an
argument:
@example
$ gprof a.out
Flat profile:
Each sample counts as 0.01 seconds.
% cumul. self self total
time seconds seconds calls us/call us/call name
68.59 2.14 2.14 62135400 0.03 0.03 step
31.09 3.11 0.97 499999 1.94 6.22 nseq
0.32 3.12 0.01 main
@end example
@noindent
The first column of the data shows that the program spends most of its
time (almost 70%) in the function @code{step}, and 30% in @code{nseq}.
Consequently efforts to decrease the run-time of the program should
concentrate on the former. In comparison, the time spent within the
@code{main} function itself is completely negligible (less than 1%).
The other columns in the output provide information on the total number
of function calls made, and the time spent in each function. Additional
output breaking down the run-time further is also produced by
@code{gprof} but not shown here. Full details can be found in the
manual ``@cite{GNU gprof---The GNU Profiler}'', by Jay Fenlason and
Richard Stallman.
@node Coverage testing with gcov
@section Coverage testing with @code{gcov}
@cindex coverage testing, with @code{gcov}
@cindex @code{gcov}, GNU coverage testing tool
The GNU coverage testing tool @code{gcov} analyses the number of times
each line of a program is executed during a run. This makes it possible
to find areas of the code which are not used, or which are not exercised
in testing. When combined with profiling information from @code{gprof}
the information from coverage testing allows efforts to speed up a
program to be concentrated on specific lines of the source code.
We will use the example program below to demonstrate @code{gcov}. This
program loops overs the integers 1 to 9 and tests their divisibility
with the modulus (@code{%}) operator.
@example
@verbatiminclude cov.c
@end example
@noindent
To enable coverage testing the program must be compiled with
the following options:
@example
$ gcc -Wall -fprofile-arcs -ftest-coverage cov.c
@end example
@noindent
@cindex @option{-fprofile-arcs} option, instrument branches
@cindex @option{fprofile-arcs} option, instrument branches
@cindex @option{-ftest-coverage} option, record coverage
@cindex @option{ftest-coverage} option, record coverage
@cindex instrumented executable, for coverage testing
@cindex branches, instrumenting for coverage testing
This creates an @dfn{instrumented} executable which contains additional
instructions that record the number of times each line of the program is
executed. The option @option{-ftest-coverage} adds instructions for
counting the number of times individual lines are executed, while
@option{-fprofile-arcs} incorporates instrumentation code for each
branch of the program. Branch instrumentation records how frequently
different paths are taken through @samp{if} statements and other
conditionals. The executable must then be run to create the coverage
data:
@example
$ ./a.out
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3
@end example
@noindent
The data from the run is written to several files with the extensions
@file{.bb} @file{.bbg} and @file{.da} respectively in the current
directory. This data can be analyzed using the @code{gcov} command and
the name of a source file:
@example
$ gcov cov.c
88.89% of 9 source lines executed in file cov.c
Creating cov.c.gcov
@end example
@noindent
The @code{gcov} command produces an annotated version of the original
source file, with the file extension @file{.gcov}, containing counts of
the number of times each line was executed:
@example
@verbatiminclude cov_c_gcov
@end example
@noindent
The line counts can be seen in the first column of the output. Lines
which were not executed are marked with hashes @samp{######}. The
command @samp{grep '######' *.gcov} can be used to find parts of a
program which have not been used.
@node How the compiler works
@chapter How the compiler works
@cindex compilation, internal stages of
@cindex stages of compilation, used internally
@cindex compiler, how it works internally
@cindex assembler, @code{as}
@cindex preprocessor, @code{cpp}
@cindex linker, @code{ld}
@cindex archiver, @code{ar}
This chapter describes in more detail how GCC transforms source files to
an executable file. Compilation is a multi-stage process involving
several tools, including the GNU Compiler itself (through the @code{gcc}
or @code{g++} frontends), the GNU Assembler @code{as}, and the GNU
Linker @code{ld}. The complete set of tools used in the compilation
process is referred to as a @dfn{toolchain}.
@menu
* An overview of the compilation process::
* The preprocessor::
* The compiler::
* The assembler::
* The linker::
@end menu
@node An overview of the compilation process
@section An overview of the compilation process
The sequence of commands executed by a single invocation of GCC consists
of the following stages:
@itemize @bullet
@item
preprocessing (to expand macros)
@item
compilation (from source code to assembly language)
@item
assembly (from assembly language to machine code)
@item
linking (to create the final executable)
@end itemize
@noindent
As an example, we will examine these compilation stages individually
using the @dfn{Hello World} program @file{hello.c}:
@example
@verbatiminclude hello.c
@end example
@noindent
Note that it is not necessary to use any of the individual commands
described in this section to compile a program. All the commands are
executed automatically and transparently by GCC internally, and can be
seen using the @option{-v} option described earlier (@pxref{Verbose
compilation}). The purpose of this chapter is to provide an
understanding of how the compiler works.
Although the @dfn{Hello World} program is very simple it uses external
header files and libraries, and so exercises all the major steps of the
compilation process.
@node The preprocessor
@section The preprocessor
@cindex preprocessor, first stage of compilation
The first stage of the compilation process is the use of the
preprocessor to expand macros and included header files. To perform
this stage, GCC executes the following command:@footnote{As mentioned
earlier, the preprocessor is integrated into the compiler in recent
versions of GCC. Conceptually, the compilation process is the same as
running the preprocessor as separate application.}
@cindex @code{.i}, preprocessed file extension for C
@cindex @code{i}, preprocessed file extension for C
@cindex extension, @code{.i} preprocessed file
@cindex file extension, @code{.i} preprocessed file
@cindex @code{.ii}, preprocessed file extension for C++
@cindex @code{ii}, preprocessed file extension for C++
@cindex extension, @code{.ii} preprocessed file
@cindex file extension, @code{.ii} preprocessed file
@example
$ cpp hello.c > hello.i
@end example
@noindent
The result is a file @file{hello.i} which contains the source code with
all macros expanded. By convention, preprocessed files are given the
file extension @file{.i} for C programs and @file{.ii} for C++ programs.
In practice, the preprocessed file is not saved to disk unless the
@option{-save-temps} option is used.
@node The compiler
@section The compiler
@cindex compiler, converting source code to assembly code
@cindex @option{-S} option, create assembly code
@cindex @option{S} option, create assembly code
The next stage of the process is the actual compilation of preprocessed
source code to assembly language, for a specific processor. The
command-line option @option{-S} instructs @code{gcc} to convert the
preprocessed C source code to assembly language without creating an
object file:
@example
$ gcc -Wall -S hello.i
@end example
@noindent
@cindex @code{.s}, assembly file extension
@cindex @code{s}, assembly file extension
@cindex extension, @code{.s} assembly file
@cindex file extension, @code{.s} assembly file
The resulting assembly language is stored in the file @file{hello.s}.
Here is what the @dfn{Hello World} assembly language for an Intel x86
(i686) processor looks like:
@example
$ cat hello.s
.file "hello.c"
.section .rodata
.LC0:
.string "Hello, world!\n"
.text
.globl main
.type main, @@function
main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
subl %eax, %esp
movl $.LC0, (%esp)
call printf
movl $0, %eax
leave
ret
.size main, .-main
.ident "GCC: (GNU) 3.3.1"
@end example
@noindent
Note that the assembly language contains a call to the external function
@code{printf}.
@node The assembler
@section The assembler
@cindex assembler, converting assembly language to machine code
The purpose of the assembler is to convert assembly language into
machine code and generate an object file. When there are calls to
external functions in the assembly source file, the assembler leaves the
addresses of the external functions undefined, to be filled in later by
the linker. The assembler can be invoked with the following command
line:
@example
$ as hello.s -o hello.o
@end example
@noindent
As with GCC, the output file is specified with the @option{-o} option.
The resulting file @file{hello.o} contains the machine instructions for
the @dfn{Hello World} program, with an undefined reference to
@code{printf}.
@node The linker
@section The linker
@cindex linker, @code{ld}
The final stage of compilation is the linking of object files to create
an executable. In practice, an executable requires many external
functions from system and C run-time (@code{crt}) libraries.
Consequently, the actual link commands used internally by GCC are
complicated. For example, the full command for linking the @dfn{Hello
World} program is:
@example
$ ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o
/usr/lib/crti.o /usr/lib/gcc-lib/i686/3.3.1/crtbegin.o
-L/usr/lib/gcc-lib/i686/3.3.1 hello.o -lgcc -lgcc_eh
-lc -lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o
/usr/lib/crtn.o
@end example
@noindent
Fortunately there is never any need to type the command above
directly---the entire linking process is handled transparently by
@code{gcc} when invoked as follows:
@example
$ gcc hello.o
@end example
@noindent
This links the object file @file{hello.o} to the C standard library, and
produces an executable file @file{a.out}:
@example
$ ./a.out
Hello, world!
@end example
@noindent
An object file for a C++ program can be linked to the C++ standard
library in the same way with a single @code{g++} command.
@node Examining compiled files
@chapter Examining compiled files
@cindex examining compiled files
@cindex compiled files, examining
This chapter describes several useful tools for examining the contents
of executable files and object files.
@menu
* Identifying files::
* Examining the symbol table::
* Finding dynamically linked libraries::
@end menu
@node Identifying files
@section Identifying files
@cindex @code{file} command, for identifying files
@cindex identifying files, with @code{file} command
@cindex object file, examining with @code{file} command
@cindex executable, examining with @code{file} command
When a source file has been compiled to an object file or executable the
options used to compile it are no longer obvious. The @command{file}
command looks at the contents of an object file or executable and
determines some of its characteristics, such as whether it was compiled
with dynamic or static linking.
For example, here is the result of the @command{file} command for a typical
executable:
@example
$ file a.out
a.out: ELF 32-bit LSB executable, Intel 80386,
version 1 (SYSV), dynamically linked (uses shared
libs), not stripped
@end example
@noindent
The output shows that the executable file is dynamically linked, and
compiled for the Intel 386 and compatible processors. A full
explanation of the output is shown below:
@table @code
@item ELF
@cindex ELF format
@cindex COFF format
The internal format of the executable file (ELF stands for ``Executable
and Linking Format'', other formats such as COFF ``Common Object File
Format'' are used on some older operating systems (e.g. MS-DOS)).
@item 32-bit
@cindex word-size, determined from executable file
The word size (for some platforms this would be 64-bit).
@item LSB
@cindex LSB, least significant byte
@cindex MSB, most significant byte
@cindex Motorola 680x0, word-order
@cindex word-ordering, endianness
@cindex endianness, word-ordering
@cindex big-endian, word-ordering
@cindex little-endian, word-ordering
Compiled for a platform with @dfn{least significant byte} first
word-ordering, such as Intel and AMD x86 processors (the alternative MSB
@dfn{most significant byte} first is used by other processors, such as
the Motorola 680x0)@footnote{The MSB and LSB orderings are also known as
big-endian and little-endian respectively (the terms originate from
Jonathan Swift's satire ``Gulliver's Travels'', 1727).}. Some
processors such as Itanium and MIPS support both LSB and MSB orderings.
@item Intel 80386
The processor the executable file was compiled for.
@item version 1 (SYSV)
@cindex SYSV, System V executable format
This is the version of the internal format of the file.
@item dynamically linked
The executable uses shared libraries (@code{statically linked} indicates
programs linked statically, for example using the @option{-static} option)
@item not stripped
@cindex @code{strip} command
The executable contains a symbol table (this can be removed with the
@command{strip} command).
@end table
@noindent
The @command{file} command can also be used on object files, where it
gives similar output. The POSIX standard@footnote{POSIX.1 (2003
edition), IEEE Std 1003.1-2003.} for Unix systems defines the behavior
of the @command{file} command.
@node Examining the symbol table
@section Examining the symbol table
@cindex symbol table, examining with @code{nm}
@cindex @code{nm} command
As described earlier in the discussion of debugging, executables and
object files can contain a symbol table (@pxref{Compiling for
debugging}). This table stores the location of functions and variables
by name, and can be displayed with the @command{nm} command:
@example
$ nm a.out
08048334 t Letext
08049498 ? _DYNAMIC
08049570 ? _GLOBAL_OFFSET_TABLE_
........
080483f0 T main
08049590 b object.11
0804948c d p.3
U printf@@GLIBC_2.0
@end example
@noindent
Among the contents of the symbol table, the output shows that the start
of the @code{main} function has the hexadecimal offset @code{080483f0}.
Most of the symbols are for internal use by the compiler and operating
system. A @samp{T} in the second column indicates a function that is
defined in the object file, while a @samp{U} indicates a function which
is undefined (and should be resolved by linking against another object
file). A complete explanation of the output of @code{nm} can be found
in the @cite{GNU Binutils} manual.
@cindex Binutils, GNU Binary Tools
The most common use of the @command{nm} command is to check whether a
library contains the definition of a specific function, by looking for a
@samp{T} entry in the second column against the function name.
@node Finding dynamically linked libraries
@section Finding dynamically linked libraries
@cindex dynamically linked libraries, examining with @code{ldd}
@cindex shared libraries, examining with @code{ldd}
@cindex @code{ldd}, dynamical loader
@cindex dependencies, of shared libraries
@cindex shared libraries, dependencies
@cindex libraries, finding shared library dependencies
When a program has been compiled using shared libraries it needs to load
those libraries dynamically at run-time in order to call external
functions. The command @command{ldd} examines an executable and
displays a list of the shared libraries that it needs. These libraries
are referred to as the shared library @dfn{dependencies} of the
executable.
For example, the following commands demonstrate how to find the shared
library dependencies of the @dfn{Hello World} program:
@example
$ gcc -Wall hello.c
$ ldd a.out
libc.so.6 => /lib/libc.so.6 (0x40020000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
@end example
@noindent
The output shows that the @dfn{Hello World} program depends on the C
library @code{libc} (shared library version 6) and the dynamic loader
library @code{ld-linux} (shared library version 2).
If the program uses external libraries, such as the math library, these
are also displayed. For example, the @code{calc} program (which uses
the @code{sqrt} function) generates the following output:
@example
$ gcc -Wall calc.c -lm -o calc
$ ldd calc
libm.so.6 => /lib/libm.so.6 (0x40020000)
libc.so.6 => /lib/libc.so.6 (0x40041000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
@end example
@noindent
The first line shows that this program depends on the math library
@code{libm} (shared library version 6), in addition to the C library and
dynamic loader library.
The @code{ldd} command can also be used to examine shared libraries
themselves, in order to follow a chain of shared library dependencies.
@node Common error messages
@chapter Common error messages
@cindex error messages, common examples
@cindex common error messages
This chapter describes the most frequent error and warning messages
produced by @code{gcc} and @code{g++}. Each case is accompanied by a
description of the causes, an example and suggestions of possible
solutions.
@menu
* Preprocessor error messages::
* Compiler error messages::
* Linker error messages::
* Runtime error messages::
@end menu
@node Preprocessor error messages
@section Preprocessor error messages
@cindex preprocessor, error messages
@table @code
@item No such file or directory
@cindex No such file or directory
This error occurs if GCC cannot find a requested file on its search
path. The file may have been specified on the command-line, or with a
preprocessor @code{#include} statement. Either the filename has been
spelled incorrectly or the directory for the file needs to be added to the
include path or link path.
Example:
@example
@verbatiminclude msg-file.c
@end example
@noindent
The program above tries to include the non-existent file @file{stdoi.h}
giving the error @samp{stdoi.h: No such file or directory}. The correct
filename should be @file{stdio.h}.
@item macro or '#include' recursion too deep
@itemx #include nested too deeply
@cindex macro or '#include' recursion too deep
@cindex include nested too deeply
This error occurs if the preprocessor encounters too many nested
@samp{#include} directives. It is usually caused by two or more files
trying to include each other, leading to an infinite recursion.
Example:
@example
@verbatiminclude msg-nest1.h
@end example
@example
@verbatiminclude msg-nest2.h
@end example
@noindent
The solution to this problem is to ensure that files do not mutually
include each other, or to use ``include guards'' (@pxref{Providing your
own templates} for an example).
@item invalid preprocessing directive #...
@cindex invalid preprocessing directive
This error indicates that the preprocessor encountered an unrecognized
@code{#} command.
Example:
@example
@verbatiminclude msg-invalidpp.c
@end example
@noindent
The preprocessor syntax requires @code{#elif} for the ``else if'' condition in
@code{#if} blocks, rather than @code{#elseif}. In the example above
an invalid directive error occurs at the incorrect usage
@code{#elseif}, but only when @code{FOO} is defined (otherwise the
preprocessor ignores everything up to the @code{#else} statement).
@cindex @code{#elif}, preprocessor directive
@cindex @code{#else}, preprocessor directive
@item warning: This file includes at least one deprecated or antiquated header.
@cindex file includes at least one deprecated or antiquated header
@cindex deprecated header in C++
@cindex antiquated header in C++
@cindex old-style C++ header files
This warning is generated for C++ programs which include old-style
library header files, such as @file{iostream.h}, instead of the modern
C++ library headers without the @file{.h} extension. The old headers
import their functions into the top-level global namespace, instead of
using the @code{std::} namespace. Note that old-style header files are
still supported, so this message is only a warning and existing programs
will continue to compile. The message is actually generated by a
@code{#warning} directive in the old header files, and not by the
preprocessor itself.
@cindex @code{#warning}, preprocessor directive
Example:
@example
@verbatiminclude msg-cppheader.c
@end example
@noindent
This program uses an old-style header file @file{iostream.h}. It could
be updated to use @code{#include <iostream>} and @code{std::cout}
instead.
@end table
@node Compiler error messages
@section Compiler error messages
@cindex compiler, error messages
@table @code
@item `@var{variable}' undeclared (first use in this function)
@cindex undeclared variable
In C and C++ variables must be declared before they can be used. This
error message indicates that the compiler has encountered a variable
name which does not have a corresponding declaration. It can be caused
by a missing declaration, or a typing error in the name. Variable names
are case-sensitive, so @code{foo} and @code{Foo} represent different
variables. To keep the output short, only the first use of an
undeclared variable is reported.
Example:
@example
@verbatiminclude msg-undeclared.c
@end example
@noindent
The variable @code{j} is not declared and will trigger the error @code{`j'
undeclared}.
@item parse error before `...'
@itemx syntax error
@cindex parse error
@cindex syntax error
These error messages occur when the compiler encounters unexpected
input, i.e. sequences of characters which do not follow the syntax of
the language. The error messages can be triggered by a missing close
bracket, brace or semicolon preceding the line of the error, or an
invalid keyword.
Example:
@example
@verbatiminclude msg-parse.c
@end example
@noindent
There is a missing semicolon after the first call to @code{printf},
giving a @code{parse error}.
@item parse error at end of input
@cindex parse error at end of input
This error occurs if the compiler encounters the end of a file
unexpectedly, such as when it has parsed an unbalanced number of opening
and closing braces. It is often caused by a missing closing brace
somewhere.
Example:
@example
@verbatiminclude msg-eoi.c
@end example
@noindent
An additional closing brace is needed in this program to prevent the
error @code{parse error at end of input}.
@item warning: implicit declaration of function `...'
@cindex implicit declaration of function
This warning is generated when a function is used without a prototype
being declared. It can be caused by failing to include a header file,
or otherwise forgetting to provide a function prototype.
Example:
@example
@verbatiminclude msg-implicitdecl.c
@end example
@noindent
The system header file @file{stdio.h} is not included, so the prototype
for @code{printf} is not declared. The program needs an initial line
@code{#include <stdio.h>}.
@item unterminated string or character constant
@cindex unterminated string or character constant
This error is caused by an opening string or character quote which does
not have a corresponding closing quote. Quotes must occur in matching
pairs, either single quotes @code{'a'} for characters or double quotes
@code{"aaa"} for strings.
Example:
@example
@verbatiminclude msg-unterm.c
@end example
@noindent
The opening quote for the string in this program does not have a
corresponding closing quote, so the compiler will read the rest of the
file as part of the string.
@item character constant too long
@cindex character constant too long
In C and C++ character codes are written using single quotes, e.g.
@code{'a'} gives the ASCII code for the letter a (67), and @code{'\n'}
gives the ASCII code for newline (10). This error occurs if single quotes
are used to enclose more than one character.
Example:
@example
@verbatiminclude msg-string2.c
@end example
@noindent
The program above confuses single-quotes and double-quotes. A sequence
of characters should be written with double quotes, e.g. @code{"Hello
World!"}. This same problem occurs in the following C++ program,
@example
@verbatiminclude msg-string2.cc
@end example
@noindent
This error can also occur if the forward slash and backslash are
confused in an escape sequence, e.g. using @code{'/n'} instead of
@code{'\n'}. The sequence @code{/n} consists of two separate
characters, @samp{/} and @samp{n}.
Note that according to the C standard there is no limit on the length of
a character constant, but the value of a character constant that
contains more than one character is implementation-defined. Recent
versions of GCC provide support multi-byte character constants, and
instead of an error the warnings @code{multiple-character character
constant} or @code{warning: character constant too long for its type}
are generated in this case.
@cindex multiple-character character constant
@cindex character constant too long
@item warning: initialization makes integer from pointer without a cast
@cindex initialization makes integer from pointer without a cast
This error indicates a misuse of a pointer in an integer context.
Technically, it is possible to convert between integer and pointer
types, but this is rarely needed outside system-level applications.
More often, this warning is the result of using a pointer without
dereferencing it (e.g. writing @code{int i = p} instead of @code{int i
= *p}).
This warning can also occur with @code{char} and @code{char *} types,
since @code{char} is an integer type.
Example:
@example
@verbatiminclude msg-char.c
@end example
@noindent
The variable @code{c} has type @code{char}, while the string @code{"\n"}
evaluates to a @code{const char *} pointer (to a 2-byte region of memory
containing the ASCII value for newline followed by a zero byte @code{'\0'},
since strings are null-terminated). The ASCII code for newline can be
found using @code{char c = '\n';}
Similar errors can occur with misuse of the macro @code{NULL},
@example
@verbatiminclude msg-null.c
@end example
@noindent
In C, the macro @code{NULL} is defined as @code{((void *)0)} in
@file{stdlib.h} and should only be used in a pointer context.
@c Note that it is important to distinguish between the ASCII character
@c @sc{NUL} (character code 0) and the null pointer @code{NULL}.
@c @example
@c int i = 0; @r{zero}
@c char c = '\0'; @r{null character, ASCII @sc{NUL}}
@c char * s = ""; @r{empty string, a pointer to '\0'}
@c void * p = NULL; @r{null pointer}
@c @end example
@item dereferencing pointer to incomplete type
@cindex dereferencing pointer to incomplete type
This error occurs when a program attempts to access the elements of
struct through a pointer without the layout of the struct being declared
first. In C and C++ it is possible to declare pointers to structs
before declaring their struct layout, provided the pointers are not
dereferenced---this is known as @dfn{forward declaration}.
Example:
@example
@verbatiminclude msg-derefincomplete.c
@end example
@noindent
This program has a forward declaration of the @code{btree} struct
@code{data}. However, the definition of the struct is needed before the
pointer can be dereferenced to access individual members.
@item warning: unknown escape sequence `...'
@cindex unknown escape sequence
This error is caused by an incorrect use of the escape character in a
string. Valid escape sequences are:
@multitable @columnfractions 0.12 .33 .33
@item
@tab @code{\n} newline
@tab @code{\t} tab
@item
@tab @code{\b} backspace
@tab @code{\r} carriage return
@item
@tab @code{\f} form feed
@tab @code{\v} vertical tab
@item
@tab @code{\a} alert (bell)
@end multitable
@noindent
The combinations @code{\\}, @code{\'}, @code{\"} and @code{\?} can be
used for individual characters. Escape sequences can also use octal
codes @code{\0}--@code{\377} and hexadecimal codes
@code{\0x00}--@code{\0xFF}.
Example:
@example
@verbatiminclude msg-unknownesc.c
@end example
@noindent
The escape sequence @code{\N} in the program above is invalid---the
correct escape sequence for a newline is @code{\n}.
@item warning: suggest parentheses around assignment used as truth value
@cindex suggest parentheses around assignment used as truth value
This warning highlights a potentially serious error, using the assignment
operator @samp{=} instead of the comparison operator @samp{==} in the
test of a conditional statement or other logical expression. While the
assignment operator can be used as part of a logical value, this is rarely
the intended behavior.
Example:
@example
@verbatiminclude msg-assign.c
@end example
@noindent
The test above should be written as @code{if (i == 1)}, otherwise the
variable @code{i} will be set to @code{1} by the evaluation of the if
statement itself. The operator @samp{=} both assigns and returns the
value of its right-hand side, causing the variable @code{i} to be
modified and the unexpected branch taken. Similar unexpected results
occur with @code{if (i = 0)} instead of @code{if (i == 0)},
except that in this case the body of the @code{if} statement would
never be executed.
This warning is suppressed if the assignment is enclosed in additional
parentheses to indicate that it is being used legitimately.
@item warning: control reaches end of non-void function
@cindex control reaches end of non-void function
A function which has been declared with a return type, such as
@code{int} or @code{double}, should always have a @code{return}
statement returning a value of the corresponding type at all
possible end points---otherwise its return value is not well-defined.
Functions declared @code{void} do not need @code{return} statements.
Example:
@example
@verbatiminclude msg-control.c
@end example
@noindent
The program above reaches the end of the @code{display} function, which has
a return type of @code{int}, without a @code{return} statement. An
additional line such as @code{return 0;} is needed.
When using @code{gcc} the @code{main} function of a C program must
return a value of type @code{int} (the exit status of the program). In
C++ the @code{return} statement can be omitted from the @code{main}
function---the return value of the C++ @code{main} function defaults
to 0 if unspecified.
@item warning: unused variable `...'
@itemx warning: unused parameter `...'
@cindex unused variable warning
@cindex unused parameter warning
These warnings indicate that a variable has been declared as a local
variable or in the parameters of a function, but has not been used
anywhere. An unused variable can be the result of a programming error,
such as accidentally using the name of a different variable in place of
the intended one.
Example:
@example
@verbatiminclude msg-unused.c
@end example
@noindent
In this program the variable @code{i} and the parameter @code{p} are
never used. Note that unused variables are reported by @option{-Wall},
while unused parameters are only shown with @option{-Wall -W}.
@item warning: passing arg of ... as ... due to prototype
@cindex passing arg of function as another type to prototype
This warning occurs when a function is called with an argument of a
different type from that specified in the prototype. The option
@option{-Wconversion} is needed to enable this warning. See
the description of @option{-Wconversion} in @ref{Additional warning
options} for an example.
@item warning: assignment of read-only location
@itemx warning: cast discards qualifiers from pointer target type
@itemx warning: assignment discards qualifiers ...
@itemx warning: initialization discards qualifiers ...
@itemx warning: return discards qualifiers ...
@cindex assignment of read-only location
@cindex cast discards qualifiers from pointer target type
@cindex assignment discards qualifiers
@cindex initialization discards qualifiers
@cindex return discards qualifiers
These warnings occur when a pointer is used incorrectly, violating a
type qualifier such as @code{const}. Data accessed through a pointer
marked as @code{const} should not be modified, and the pointer itself
can only be assigned to other pointers that are also marked
@code{const}.
Example:
@example
@verbatiminclude msg-const.c
@end example
@noindent
This program attempts to modify constant data, and to discard the
@code{const} property of the argument @code{s} in the return value.
@item initializer element is not a constant
@cindex initializer element is not a constant
In C, global variables can only be initialized with constants, such as
numeric values, @code{NULL} or fixed strings. This error occurs if a
non-constant value is used.
Example:
@example
@verbatiminclude msg-init.c
@end example
@noindent
This program attempts to initialize two variables from other variables.
In particular, the stream @code{stdout} is not required to be a constant
by the C standard (although on some systems it is a constant). Note
that non-constant initializers are allowed in C++.
@end table
@node Linker error messages
@section Linker error messages
@cindex linker, error messages
@table @code
@item file not recognized: File format not recognized
@cindex file not recognized
@cindex file format not recognized
GCC uses the extension of a file, such as @file{.c} or @file{.cc}, to
determine its content. If the extension is missing GCC cannot recognize
the file type and will give this error.
Example:
@example
@verbatiminclude msg-ext
@end example
@noindent
If the program above is saved in a file @file{hello} without any
extension then compiling it will give the error:
@example
$ gcc -Wall hello
hello: file not recognized: File format not
recognized
collect2: ld returned 1 exit status
@end example
@noindent
The solution is to rename the file to the correct extension, in this
case @file{hello.c}.
@item undefined reference to `foo'
@itemx collect2: ld returned 1 exit status
@cindex undefined reference error
@cindex collect2: ld returned 1 exit status
@cindex ld returned 1 exit status
This error occurs when a program uses a function or variable which is
not defined in any of the object files or libraries supplied to the
linker. It can be caused by a missing library or the use of an
incorrect name. In the error message above, the program
@file{collect2} is part of the linker.
Example:
@example
@verbatiminclude msg-undef.c
@end example
@noindent
If this program is compiled without linking to a library or object file
containing the function @code{foo()} there will be an undefined
reference error.
@item /usr/lib/crt1.o(.text+0x18): undefined reference to `main'
@cindex undefined reference to 'main'
This error is a special case of the error above, when the missing
function is @code{main}. In C and C++, every program must have a
@code{main} function (where execution starts). When compiling an
individual source file without a @code{main} function, use the option
@option{-c} (@pxref{Creating object files from source files}).
@end table
@node Runtime error messages
@section Runtime error messages
@cindex runtime error messages
@table @code
@item error while loading shared libraries:
@itemx cannot open shared object file: No such file or directory
@cindex error while loading shared libraries
@cindex cannot open shared object file
@cindex No such file or directory
The program uses shared libraries, but the necessary shared library
files cannot be found by the dynamic linker when the program starts.
The search path for shared libraries is controlled by the environment
variable @env{LD_LIBRARY_PATH} (@pxref{Shared libraries and static
libraries}).
@item Segmentation fault
@itemx Bus error
@cindex segmentation fault
@cindex bus error
@cindex null pointer
@cindex uninitialized pointer
@cindex @code{scanf}, incorrect usage warning
These runtime messages indicate a memory access error.
Common causes include:
@itemize @bullet
@item dereferencing a null pointer or uninitialized pointer
@item out-of-bounds array access
@item incorrect use of @code{malloc}, @code{free} and related functions
@item use of @code{scanf} with invalid arguments
@end itemize
There is a subtle difference between segmentation faults and bus errors.
A segmentation fault occurs when a process tries to access memory
protected by the operating system. A bus error occurs when valid memory
is accessed in an incorrect way (for example, trying to read an
@dfn{unaligned} value on architectures where values must be aligned with
4-byte offsets).
@item floating point exception
@cindex floating point exception
This runtime error is caused by an arithmetic exception, such as
division by zero, overflow, underflow or an invalid operation (e.g.
taking the square root of @math{-1}). The operating system determines
which conditions produce this error. On GNU systems, the functions
@code{feenableexcept} and @code{fedisableexcept} can be used to trap or
mask each type of exception.
@item Illegal instruction
@cindex illegal instruction error
This error is produced by the operating system when an illegal machine
instruction is encountered. It occurs when code has been compiled for
one specific architecture and run on another.
@end table
@ignore
@table @code
@item function declaration isn't a prototype
@item comparison between signed and unsigned
@item too few arguments for format
@item ... used with ... format
@item declared inside parameter list
@item may not appear in macro parameter list
@item ? without following :
@itemx : without preceding ?
@itemx signed and unsigned type in conditional expression
@item conflicting types for ....
@item /* within comment
@item type defaults to `int' in declaration of ...
@item data definition has no type or storage class
@item pointer targets differ in signedness
@item storage size of ... isn't known
@item integer overflow in expression
@item no previous prototype for ...
@item redundant redeclaration of ...
@item array subscript has type char
@item array subscript is not an integer
@item cast from pointer to integer of different size
@item return type defaults to int
@item missing braces around initializer
@item unterminated comment
@item suggest explicit braces to avoid ambiguous else
@item invalid lvalue in assignment
@item function returns address of local variable
@item comparison is always false due to limited range of datatype
@itemx comparison is always true due to limited range of datatype
can be caused by signed vs unsigned char
@item excess elements in scalar initializer
@item excess elements in struct initializer
@item excess elements in array initializer
@item invalid operands to binary ...
@item return with a value in function returning void
@item ... is a GCC extension
@item empty body in an if-statement
@item empty body in an else-statement
@item invalid storage class for function ...
@item unknown escape sequence ...
@item variable or field ... declared void
@item argument ... doesn't match prototype
@item subscripted value is neither array nor pointer
@item braces around scalar initializer
@item number of arguments doesn't match prototype
@item large integer implicitly truncated to unsigned type
@item integer constant is too large for ... type
@item overflow in implicit constant conversion
@item nested extern declaration of ...
@item parameter has incomplete type
@item return with no value, in function returning non-void
@item no return statement in function returning non-void
@item this function may return with or without a value
@item ... with different width due to prototype
@item declaration of ... shadows a global declaration
@item declaration of ... shadows a previous local declaration
@item ... of read-only variable
@item initializer element is not computable at load time
@item empty character constant
@item ... has an incomplete type
@item integer constant is so large that it is unsigned
@item backslash and newline separated by space
@item array size missing in ...
@item unrecognized format specifier ...
@item ... as unsigned due to prototype
@item ... as signed due to prototype
@item overflow in constant expression
@item floating point overflow in expression
@item for loop initial declaration used outside C99 mode
@item switch quantity is not an integer
@item too many decimal points in number
@item storage size of ... isn't constant
@item as floating rather than integer due to prototype
@item invalid conversion from ... to ...
@item no matching function for call to ...
@item shadow...
@end table
@end ignore
@node Getting help
@chapter Getting help
@cindex getting help
If you encounter a problem not covered by this introduction, there are several
reference manuals which describe GCC and language-related topics in more
detail (@pxref{Further reading}). These manuals contain answers to
common questions, and careful study of them will usually yield a
solution.
Alternatively, there are many companies and consultants who offer
commercial support for programming matters related to GCC on an hourly
or ongoing basis. For businesses this can be a cost-effective way to
obtain high-quality support.
@cindex support, commercial
@cindex commercial support
A directory of free software support companies and their current rates
can be found on the GNU Project
website.@footnote{@uref{http://www.gnu.org/prep/service.html}} With free
software, commercial support is available in a free market---service
companies compete in quality and price, and users are not tied to any
particular one. In contrast, support for proprietary software is
usually only available from the original vendor.
@cindex enhancements, to GCC
A higher-level of commercial support for GCC is available from companies
involved in the development of the GNU compiler toolchain itself. A
listing of these companies can be found in the ``Development Companies''
section of the publisher's webpage for this
book.@footnote{@uref{http://www.network-theory.co.uk/gcc/intro/}} These
companies can provide services such as extending GCC to generate code
for new CPUs or fixing bugs in the compiler.
@node Further reading
@unnumbered Further reading
@cindex manuals, for GNU software
The definitive guide to GCC is the official reference manual,
``@cite{Using GCC}'', published by GNU Press:
@cindex Using GCC (Reference Manual)
@cindex GNU Compilers, Reference Manual
@quotation
@cite{Using GCC (for GCC version 3.3.1)} by Richard M. Stallman and the GCC Developer Community
(Published by GNU Press, ISBN 1-882114-39-6)
@end quotation
@noindent
This manual is essential for anyone working with GCC because it
describes every option in detail. Note that the manual is updated when
new releases of GCC become available, so the ISBN number may change in
the future.
If you are new to programming with GCC you will also want to learn how
to use the GNU Debugger GDB, and how to compile large programs easily
with GNU Make. These tools are described in the following manuals:
@cindex GNU GDB Manual
@cindex GNU Make Manual
@quotation
@cite{Debugging with GDB: The GNU Source-Level Debugger}
by Richard M. Stallman, Roland Pesch, Stan Shebs, et al. (Published by GNU Press, ISBN 1-882114-88-4)
@end quotation
@quotation
@cite{GNU Make: A Program for Directing Recompilation}
by Richard M. Stallman and Roland McGrath (Published by GNU Press, ISBN
1-882114-82-5)
@end quotation
@noindent
For effective C programming it is also essential to have a good
knowledge of the C standard library. The following manual documents all
the functions in the GNU C Library:
@cindex GNU C Library Reference Manual
@quotation
@cite{The GNU C Library Reference Manual}
by Sandra Loosemore with Richard M. Stallman, et al (2 vols) (Published
by GNU Press, ISBN 1-882114-22-1 and 1-882114-24-8)
@end quotation
@noindent
@cindex GNU Press, manuals
Be sure to check the website @uref{http://www.gnupress.org/} for the
latest printed editions of manuals published by GNU Press. The manuals
can be purchased online using a credit card at the FSF
website@footnote{@uref{http://order.fsf.org/}} in addition to being
available for order through most bookstores using the ISBNs. Manuals
published by GNU Press raise funds for the Free Software Foundation and
the GNU Project.
@cindex shell quoting
Information about shell commands, environment variables and shell-quoting
rules can be found in the following book:
@quotation
@uref{http://www.network-theory.co.uk/bash/manual/,@cite{The GNU Bash Reference Manual},@cite{The GNU Bash Reference Manual}}
by Chet Ramey and Brian Fox
(Published by Network Theory Ltd, ISBN 0-9541617-7-7)
@end quotation
@noindent
Other GNU Manuals mentioned in this book (such as @cite{GNU gprof---The
GNU Profiler} and @cite{The GNU Binutils Manual}) were not available in
print at the time this book went to press. Links to online copies can
be found at the publisher's webpage for this
book.@footnote{@uref{http://www.network-theory.co.uk/gcc/intro/}}
The official GNU Project webpage for GCC can be found on the GNU website
at @uref{http://www.gnu.org/software/gcc/}. This includes a list of
frequently asked questions, as well as the GCC bug tracking database and
a lot of other useful information about GCC.
There are many books about the C and C++ languages themselves. Two of
the standard references are:
@cindex reference books
@cindex C language, further reading
@cindex books, further reading
@cindex Kernighan and Ritchie, @cite{The C Programming Language}
@quotation
@cite{The C Programming Language} (ANSI edition)
Brian W. Kernighan, Dennis Ritchie (ISBN 0-13110362-8)
@end quotation
@quotation
@cite{The C++ Programming Language} (3rd edition)
Bjarne Stroustrup (ISBN 0-20188954-4)
@end quotation
@noindent
@cindex C library, standard
@cindex standards, C, C++ and IEEE arithmetic
@cindex IEEE arithmetic standard, printed form
@cindex C/C++ languages, standards in printed form
@cindex ISO standards for C/C++ languages, available as books
@cindex ANSI standards for C/C++ languages, available as books
Anyone using the C and C++ languages in a professional context should
obtain a copy of the official language standards, which are also
available as printed books:
@quotation
@cite{The C Standard: Incorporating Technical Corrigendum 1}
(Published by Wiley, ISBN 0-470-84573-2)
@end quotation
@quotation
@cite{The C++ Standard}
(Published by Wiley, ISBN 0-470-84674-7)
@end quotation
@noindent
For reference, the C standard number is ISO/IEC 9899:1990, for the
original C standard published in 1990 and implemented by GCC. A revised
C standard ISO/IEC 9899:1999 (known as C99) was published in 1999, and
this is mostly (but not yet fully) supported by GCC. The C++ standard
is ISO/IEC 14882.
@cindex IEEE-754 standard
The floating-point arithmetic standard IEEE-754 is important for any
programs involving numerical computations. The standard is available
commercially from the IEEE, and is also described in the following book:
@quotation
@cite{Numerical Computing with IEEE Floating Point Arithmetic}
by Michael Overton (Published by SIAM, ISBN 0-89871-482-6).
@end quotation
@noindent
The book includes many examples to illustrate the rationale for the
standard.
@node Acknowledgements
@unnumbered Acknowledgements
Many people have contributed to this book, and it is important to record
their names here:
Thanks to Gerald Pfeifer, for his careful reviewing and numerous
suggestions for improving the book.
Thanks to Andreas Jaeger, for information on AMD64 and multi-architecture
support, and many helpful comments.
Thanks to David Edelsohn, for information on the POWER/PowerPC series of
processors.
Thanks to Jamie Lokier, for research.
Thanks to Martin Leisner, Mario Pernici, Stephen Compall and Nigel
Lowry, for helpful corrections.
Thanks to Gerard Jungman, for useful comments.
Thanks to Steven Rubin, for generating the chip layout for the cover
with Electric.
And most importantly, thanks to Richard Stallman, founder of the GNU
Project, for writing GCC and making it free software.
@page
@node Other books from the publisher
@unnumbered Other books from the publisher
@include books.texi
@node Free software organizations
@unnumbered Free software organizations
@include associations.texi
@ifnotinfo
@node GNU Free Documentation License
@unnumbered GNU Free Documentation License
@include fdl.texi
@end ifnotinfo
@node Index
@unnumbered Index
@printindex cp
@ifset extrablankpages
@comment final page must be blank for printed version
@page
@headings off
@*
@c @page
@c @*
@c @page
@c @*
@c @page
@c @*
@end ifset
@bye
|