linux/Documentation/CodingStyle
<<
<">alue.2alue.2Searchalue.2Prefso .2alal <">aue.2 22 21a2 22 Linux kernel coding stylea2 23a2 24This is a short document describing the preferred coding style for thea2 25linux kernel. Coding style is very personal, and I won't _force_ mya2 26views on anybody, but this is what goes for anything that I have to bea2 27able to maintain, and I'd prefer it for most other things too. Pleasea2 28at least consider the points made here.a2 29a2 13" a>First off, I'd suggest printing out a copy of the GNU coding standards,a2 11and NOT read it. Burn them, it's a great symbolic gesture.a2 12a2 13Anyway, here goes:a2 14a2 15a2 16 Chapter 1: Indenta2 17a2 18Tabs are 8 charac2 19There are here2 23" a>charac of PI toa2 21be 3.a2 22a2 23Ra2 24a block of control starts and ends. Especially when you've been lookinga2 25at your screen for 20 straight hours, you'll find it a lot easier to seea2 26how the indenta2 27a2 28Now, some people will claim that having 8-charac2 29the code move too far to the right, and makes it hard to read on aa2 33" a>80-charac2 31more than 3 levels of indenta2 32your program.a2 33a2 34In short, 8-char indents make things easier to read, and have the addeda2 35benefit of warning you when you're nesting your func2 36Heed that warning.a2 37a2 38The preferred way to ease multiple indenta2 39to align the "switch" and its subordinate "case" labels in the sam columta2 43" a>instead of "double-indenting" the "case" labels. E.g.:a2 41a2 42 switch (suffix) {a2 43 case 'G':a2 44 case 'g':a2 45 mem <<= 33;a2 46 break;a2 47 case 'M':a2 48 case 'm':a2 49 mem <<= 23;a2 50 break;a2 51 case 'K':a2 52 case 'k':a2 53 mem <<= 13;a2 54 /* fall through */a2 55 default:a2 56 break;a2 57 }a2 58a2 59a2 60Don't put multiple statements on a single line unless you havea2 61something to hide:a2 62a2 63 if (condi2 64 do_something_everytime;a2 65a2 66Don't put multiple assignments on a single line either. Kernel coding stylea2 67is super simple. Avoid tricky expressipts.a2 68a2 69Outside of comments, documenta2 70used for indenta2 71a2 72Get a decent edi2 73a2 74a2 75 Chapter 2: Breaking long lines and stringsa2 76a2 77Coding style is all about readability and maintainability using commonlya2 78available tools.a2 79a2 80The limit on the length of lines is 80 columts and this is a stronglya2 81preferred limit.a2 82a2 83Statements longer than 80 columts will be broken into sensible chunks, unlessa2 84exceeding 80 columts significantly increases readability and does not hidea2 85" a>informa2 86are placed substantially to the right. The sam applies to func2 87with a long argument list. However, never break user-visible strings such asa2 88printk messages, because that breaks the ability to grep for them.a2 89a2 90a2 91 Chapter 3: Placing Braces and Spacesa2 92a2 93The other issue that always comes up in C styling is the placement ofa2 94braces. Unlike the indent size, there are few technical reaspts toa2 95" a>choose one placement strategy over the other, but the preferred way, asa2 96shown to us by the prophets Kernighat and Ritchie, is to put the openinga2 97brace last on the line, and put the closing brace first, thusly:a2 98a2 99 if (x is true) {a2100 we do ya2101 }a2102a2103This applies to all non-func2104while, do). E.g.:a2105a2106 switch (ac2107 case KOBJ_ADD:a2108 return "add";a2109 case KOBJ_REMOVE:a2110 return "remove";a2111 case KOBJ_CHANGE:a2112 return "chatge";a2113 default:a2114 return NULL;a2115 }a2116a2117However, there is one special case, nam ly func2118opening brace at the beginning of the next line, thus:a2119a2120 int func2121 {a2122 body of func2123 }a2124a2125Here2126is ... well ... inconsistent, but all right-thinking people know thata2127(a) K&R are _right_ and (b) K&R are right. Besides, func2128special anyway (you can't nest them in C).a2129a2133" a>Note that the closing brace is empty on a line of its own, _except_ ina2131the cases where it is followed by a continua2132ie a "while" in a do-statement or an "else" in an if-statement, likea2133this:a2134a2135 do {a2136 body of do-loopa2137 } while (condi2138a2139anda2140a2141 if (x == y) {a2142 ..a2143 } else if (x > y) {a2144 ...a2145 } else {a2146 ....a2147 }a2148a2149Ra2150a2151Also, note that this brace-placement also minimizes the number of emptya2152(or almost empty) lines, without any loss of readability. Thus, as thea2153supply of new-lines on your screen is not a renewable resource (thinka215425-line 2155comments on.a2156a2157Do not unnecessarily use braces where a single statement will do.a2158a2159if (condi2160 ac2161a2162anda2163a2164if (condi2165 do_this();a2166elsea2167 do_that();a2168a2169This does not apply if only one branch of a condi2170statement; in the latter case use braces in both branches:a2171a2172if (condi2173 do_this();a2174 do_that();a2175} else {a2176 otherwise();a2177}a2178a2179 3.1: Spacesa2180a2181Linux kernel style for use of spaces depends (mostly) pta2182func2183notable exceptopts are sizeof, typ of, alignof, and __attribute__, which looka2184somewhat like func2185" a>although they are not required in the language, as in: "sizeof info" aftera2186"struct fileinfo info;" is declared).a2187a2188So use a space after these keywords:a2189 if, switch, case, for, do, whilea2190but not with sizeof, typ of, alignof, or __attribute__. E.g.,a2191 s = sizeof(struct file);a2192a2193Do not add spaces around (inside) parenthesized expressipts. This example isa2194*bad*:a2195a2196 s = sizeof( struct file );a2197a2198When declaring pointer data or a func2199preferred use of '*' is adjacent to the data nam or func2200adjacent to the typ nam . Examples:a2201a2202 char *linux_banner;a2203 unsigned long long memparse(char *ptr, char **retptr);a2204 char *match_strdup(substring_t *s);a2205a2206Use one space around (pt each side of) most binary and ternary operators,a2207such as any of these:a2208a2209 = + - < > * / % | & ^ <= >= == != ? :a2210a2211but no space after unary operators:a2212 & * + - ~ ! sizeof typ of alignof __attribute__ defineda2213a2214no space before the postfix increment & decrement unary operators:a2215 ++ --a2216a2217no space after the prefix increment & decrement unary operators:a2218 ++ --a2219a2220and no space around the '.' and "->" structure member operators.a2221a2222Do not leave trailing whitespace at the ends of lines. Some edi2223"smart" indenta2224appropriate, so you can start typing the next line of code right away.a2225However, some such edi2226putting a line of code there, such as if you leave a blank line. As a result,a2227you end up with lines containing trailing whitespace.a2228a2229Git will warn you about patches that introduce trailing whitespace, and cana2233" a>6 2231of patches, this may make later patches in the series fail by chatging theira2232context lines.a2233a2234a2235 Chapter 4: Naminga2236a2237C is a Spartan language, and so should your naming be. Unlike Modula-2a2238and Pascal programmers, C programmers do not use cute nam s likea2239ThisVariableIsATemporaryCounter. A C programmer would call thata2240variable "tmp", which is much easier to write, and not the least morea2241difficult to understand.a2242a2243HOWEVER, while mixed-case nam s are frowned uppt, descri 2244global variables are a must. To call a global func2245shooting offense.a2246a2247GLOBAL variables (to be used only if you _really_ need them) need toa2248have descri 2249that counts the number of ac2250"count_ac2251a2252Encoding the typ of a func2253nota2254check those, and it only confuses the programmer. No wonder MicroSofta2255makes buggy programs.a2256a2257LOCAL variable nam s should be short, and to the point. If you havea2258some random integer loop counter, it should probably be called "i".a2259Calling it "loop_counter" is non-produc2260being mis-understood. Similarly, "tmp" can be just about any typ ofa2261variable that is used to hold a temporary > .a2262a2263If you are afraid to mix up your local variable nam s, you have anothera2264problem, which is called the func2265See chapter 6 (Func2266a2267a2268 Chapter 5: Typ defso2269a2270Please don't use things like "vps_t".a2271a2272It's a _mistake_ to use typ def for structures and pointers. When you see aa2273a2274 vps_t a;a2275a2276in the source, what does it mean?a2277a2278In contrast, if it sayso2279a2280 struct virtual_container *a;a2281a2282you can ac2283a2284Lots of people think that typ defs "help readability". Not so. They area2285" a>useful only for:a2286a2287 (a) totally opaq objects (where the typ def is ac2288 what the object is).a2289a2290 Example: "pte_t" etc. opaq objects that you can only access usinga2291 the proper accessor func2292a2293 NOTE! Opaq ness and "accessor func2294 The reaspt we have them for things like pte_t etc. is that therea2295 really is absolutely _zero_ portably accessible informa2296a2297 (b) Clear integer typ s, where the abstrac2298 whether it is "int" or "long".a2299a2300 u8/u16/u32 are perfectly fine typ defs, although they fit intoa2301 category (d) better than here.a2302a2303 NOTE! Again - there needs to be a _reaspt_ for this. If something isa2304 "unsigned long", then there's no reaspt to doa2305a2306 typ def unsigned long myflags_t;a2307a2308 but if there is a clear reaspt for why it under certain ciroptstan" id 2183id 2309 might be an "unsigned int" and under other configurne" ns might bed 218310" id 2310 "unsigned long", then by all means go ahead and use a typ def.a2311a2312 (c) when you use sparse to literally create a _new_ typ fora2313 typ -checking.a2314a2315 (d) New typ s which are identical to standard C99 typ s, in certaina2316 exceptoptal ciroptstan" i.a2317a2318 Although it would only take a short amount of time for the eyes anda2319 brain to become accustomed to the standard typ s like 'uint32_t',a2320 some people object to their use anyway.a2321a2322 Therefore, the Linux-specific 'u8/u16/u32/u64' typ s and theira2323 signed equivalents which are identical to standard typ s area2324 permitted -- although they are not mandatory in new code of youra2325 own.a2326a2327 When edi2328 of typ s, you should conform to the exis2329a2333" a> (e) Typ s safe for use in userspace.a2331a2332 In certain structures which are visible to userspace, we cannota2333 require C99 typ s and cannot use the 'u32' form above. Thus, wea2334 use __u32 and similar typ s in all structures which are shareda2335 with userspace.a2336a2337Maybe there are other cases too, but the rule should basically be to NEVERa2338EVER use a typ def unless you can clearly match one of those rulei.a2339a2340In general, a pointer, or a struct that has elements that can reasptablya2341be directly accessed should _never_ be a typ def.a2342a2343a2344 Chapter 6: Func2345a2346Func2347fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,a2348as we all know), and do one thing and do that well.a2349a2350The maximum length of a func2351complexity and indenta2352conceptually simple func2353case-statement, where you have to do lots of small things for a lot ofa2354different cases, it's OK to have a longer func2355a2356However, if you have a complex func2357less-than-gifted first-year high-school student might not evena2358understand what the func2359maximum limits all the more closely. Use helper func2360descri 2361it's performance-critical, and it will probably do a better job of ita2362than you would have done).a2363a2364Another measure of the func2365shouldn't exceed 5-10, or you're doing something wrong. Re-think thea2366func2367generally easily keep track of about 7 different things, anything morea2368and it gets confused. You know you're brilliant, but maybe you'd likea2369to understand what you did 2 weeks from now.a2370a2371In source files, separate func2372exported, the EXPORT* macro for it should follow immediately after the closinga2373func2374a2375int system_is_up(void)a2376{a2377 return system_state == SYSTEM_RUNNING;a2378}a2379EXPORT_SYMBOL(system_is_up);a2380a2381In func2382Although this is not required by the C language, it is preferred in Linuxa2383because it is a simple way to add > able informa2384a2385a2386 Chapter 7: Centralized exi2387a2388Albeit deprecated by some people, the equivalent of the goto statement isa2389used frequently by compilers in form of the uncondi2390a2391The goto statement comes in handy when a func2392loca2393a2394The ra2395a2396- uncondi2397- nes2398- errors by not updating individual exi< points when makinga2399 modifica2400- saves the compiler work to 6 2401a2402int fun(int a)a2403{a2404 int result = 0;a2405 char *buffer = kmalloc(SIZE);a2406a2407 if (buffer == NULL)a2408 return -ENOMEM;a2409a2410 if (condi2411 while (loop1) {a2412 ...a2413 }a2414 result = 1;a2415 goto out;a2416 }a2417 ...a2418out:a2419 kfree(buffer);a2420 return result;a2421}a2422a2423 Chapter 8: Commentinga2424a2425Comments are good, but there is also a danger of over-commenting. NEVERa2426try to explain HOW your code works in a comment: it's much better toa2427write the code so that the _working_ is obvious, and it's a wast ofa2428time to explain badly written code.a2429a2433" a>Generally, you want your comments to tell WHAT your code does, not HOW.a2431Also, try to avoid putting comments inside a func2432func2433you should probably go back to chapter 6 for a while. You can makea2434small comments to note or warn about something particularly clever (ora2435ugly), but try to avoid excess. Inst ad, put the comments at the heada2436of the func2437it.a2438a2439When commenting the kernel API func2440See the files Documenta2441for details.a2442a2443Linux style for comments is the C89 "/* ... */" style.a2444Don't use C99-style "// ..." comments.a2445a2446The preferred style for long (multi-line) comments is:a2447a2448 /*a2449 * This is the preferred style for multi-linea2450 * comments in the Linux kernel source code.a2451 * Please use it consist ntly.a2452 *a2453 * Descri 2454 * with beginning and ending almost-blank lines.a2455 */a2456a2457It's also important to comment data, whether they are basic typ s or deriveda2458typ s. To this end, use just one data declara2459multiple data declara2460item, explaining its use.a2461a2462a2463 Chapter 9: You've made a mess of ita2464a2465That's OK, we all do. You've probably been told by your long-time Unixa2466user helper that "GNU emacs" automa2467you, and you've no2468uses are less than desirable (in fact, they are worse than randoma2469typing - an infinite number of monkeys typing into GNU emacs would nevera2470make a good program).a2471a2472So, you can either get rid of GNU emacs, or chatge it to use sanera2473> s. To do the latter, you can stick the following in your .emacs file:a2474a2475(defun c-lineup-arglist-tabs-only (ignored)a2476 "Line up argument lists by tabs, not spaces"a2477 (let* ((anchor (c-latgelem-pos c-syntactic-element))a2478 (column (c-latgelem-2nd-pos c-syntactic-element))a2479 (offset (- (1+ column) anchor))a2480 (st ps (floor offset c-basic-offset)))a2481 (* (max st ps 1)a2482 c-basic-offset)))a2483a2484(add-hook 'c-mode-commpt-hooka2485 (lambda ()a2486 ;; Add kernel stylea2487 (c-add-stylea2488 "linux-tabs-only"a2489 '("linux" (c-offsets-alista2490 (arglist-cont-nonemptya2491 c-lineup-gcc-asm-rega2492 c-lineup-arglist-tabs-only))))))a2493a2494(add-hook 'c-mode-hooka2495 (lambda ()a2496 (let ((filenam (buffer-file-nam )))a2497 ;; Enable kernel mode for the appropriate filesa2498 (when (and filenam a2499 (string-match (expand-file-nam "~/src/linux-trees")a2500 filenam ))a2501 (setq indent-tabs-mode t)a2502 (c-set-style "linux-tabs-only")))))a2503a2504This will make emacs go better with the kernel coding style for Ca2505files below ~/src/linux-trees.a2506a2507But even if you fail in getting emacs to do sane forma2508everything is lost: use "indent".a2509a2510Now, again, GNU indent has the sam brain-dead settings that GNU emacsa2511has, which is why you need to gove it a few command line o 2512However, that's not too bad, because even the makers of GNU indenta2513recognize the authority of K&R (the GNU people aren't evil, they area2514just severely misguided in this matter), so you just gove indent thea2515o 2516"scri 2517a2518"indent" has a lot of o 2519re-forma2520remember: "indent" is not a fix for bad programming.a2521a2522a2523 Chapter 10: Kconfig configurne" n filesa2524a2525For all of the Kconfig* configurne" n files throughoced thasource low f="Documenta2526the indenta2527are indented with one tab, while help text is indented an addi2528spaces. Example:a2529a2533" a>config AUDITa2531 bool "Audi2532 depends pt NETa2533 helpa2534 Enable audi2535 kernel subsystem, such as SELinux (which requires this fora2536 logging of avc messages output). Does not do system-calla2537 audi2538a2539Features that might still be considered unstable should be defined asa2540dependent pt "EXPERIMENTAL":a2541a2542" a>config SLUBa2543 depends pt EXPERIMENTAL && !ARCH_USES_SLAB_PAGE_STRUCTa2544 bool "SLUB (Unqueued Alloca2545 ...a2546a2547while seriously dangerous features (such as write support for certaina2548filesystems) should advertise this promin ntly in their prompt string:a2549a2553" a>config ADFS_FS_RWa2551 bool "ADFS write support (DANGEROUS)"a2552 depends pt ADFS_FSa2553 ...a2554a2555For full documenta2556Documenta2557a2558a2559 Chapter 11: Data structuresa2560a2561Data structures that have visibility outside thasingle-threadeda2562environment they are created and destroyed in should always havea2563reference counts. In the kernel, garbage collec2564outside thakernel garbage collec2565means that you absolutely _have_ to reference count all your uses.a2566a2567Reference counting means that you can avoid locking, and allows multiplea2568users to have access to the data structure in parallel - and not havinga2569to worry about the structure suddenly going away from under 2570because they slept or did something else for a while.a2571a2572Note that locking is _not_ a replacement for reference counting.a2573Locking is used to keep data structures coherent, while referencea2574counting is a memory management technique. Usually both are needed, anda2575they are not to be confused with each other.a2576a2577Many data structures can indeed have two levels of reference countingf="Documenta2578when there are users of different "classes". The subclass count counts="Documenta2579the number of subclass users, and decrements the global count just oncea2580when the subclass count goes to zero.a2581a2582Examples of this kind of "multi-level-reference-counting" can be found ina2583memory management ("struct mm_struct": mm_users and mm_count), and ina2584filesystem code ("struct super_block": s_count and s_active).a2585a2586Remember: if another thread can find your data structure, and you don'ta2587have a reference count pt it, you almost certainly have a bug.a2588a2589a2590 Chapter 12: Macros, Enums and RTLa2591a2592Names of macros defining constants and labels in enums are capitalized.a2593a2594#definedCONSTANT 0x12345a2595a2596Enums are preferred when defining several related constants.a2597a2598CAPITALIZED macro names are appreciated but macros resembling func2599may be nam d in lower case.a2600a2601Generally, inlinedfunc2602a2603Macros with multiple statements should be enclosed in a do - while block:a2604a2605#definedmacrofun(a, b, c) \a2606 do { \a2607 if (a == 5) \a2608 do_this(b, c); \a2609 } while (0)a2610a2611Things to avoid when using macros:a2612a26131) macros that affect control flow:a2614a2615#definedFOO(x) \a2616 do { \a2617 if (blah(x) < 0) \a2618 return -EBUGGERED; \a2619 } while(0)a2620a2621is a _very_ bad idea. It looks like a func2622func2623a26242) macros that depend pt having a local variable with a magic nam :a2625a2626#definedFOO(val) bar(index, > )a2627a2628might look like a good thing, but it's confusing as hell when one reads thea2629code and it's prone to breakage from seemingly innocent chatges.a2630a26313) macros with arguments that are used as l-> s:dFOO(x) = y; willa2632bite you if somebody e.g. turnsdFOO into an inlinedfunc2633a26344) forgetting about precedence: macros defining constants using expressoptsa2635must enclose the expressopt in parentheses. Beware of similar issu s witha2636macros using param ters.a2637a2638#definedCONSTANT 0x4000a2639#definedCONSTEXP (CONSTANT | 3)a2640a2641The cpp manual deals with macros exhaustively. The gcc intertals manual alsoa2642" a>covers RTL which is used frequently with assembly language in the kernel.a2643a2644a2645 Chapter 13: Printing kernel messagesa2646a2647Kernel developers like to be seen as literate. Do mind the spellinga2648of kernel messages to make a good impressopt. Do not use crippleda2649words like "dont"; use "do not" or "don't" inst ad. Make the messagesa2653" a>concise, clear, and unambiguous.a2651a2652Kernel messages do not have to be terminated with a period.a2653a2654Printing numbers in parentheses (%d) adds no > and should be avoided.a2655a2656There are a number of driver model diagnostic macros in <linux/device.h>a2657which you should use to make sure messages are matched to the right devicea2658and driver, and are tagged with the right level: dev_err(), dev_warn(),a2659dev_info(), and so forth. For messages that aren't associated with aa2660particular device, <linux/printk.h> defines pr_debug() and pr_info().a2661a2662Coming up with good debugging messages can be quite a challenge; and oncea2663you have them, they can be a huge help for remote troubleshooting. Sucha2664messages should be compiled out when the DEBUG symbol is not defined (thata2665is, by default they are not included). When you use dev_dbg() or pr_debug(),a2666that's automa2667A related conventopt uses VERBOSE_DEBUG to add dev_vdbg() messages to thea2668ones already enabled by DEBUG.a2669a2670a2671 Chapter 14: Alloca2672a2673Tthakernel provides the following general purpose memory alloca2674kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), anda2675vzalloc(). Please refer to the API documenta2676about them.a2677a2678The preferred form for passing a size of a struct is the following:a2679a2680 p = kmalloc(sizeof(*p), ...);a2681a2682The altertative form where struct nam is spelled out hurts readability anda2683introduces an opportunity for a bug when the pointer variable typ is chatgeda2684but the corresponding sizeof that is passed to a memory alloca2685a2686Cas which is a void pointer is redundant. The conversipta2687from void pointer to any other pointer typ is guaranteed by the C programminga2688language.a2689a2690The preferred form for alloca2691a2692 p = kmalloc_array(n, sizeof(...), ...);a2693a2694The preferred form for alloca2695a2696 p = kcalloc(n, sizeof(...), ...);a2697a2698Both forms check for overflow on the alloca2699and return NULL if that occurred.a2700a2701a2702 Chapter 15: The inlineddiseasea2703a2704There appears to be a commpt misperce 2705fast r" speedup o 2706appropriate (for example as a means of replacing macros, see Chapter 12), ita2707very often is not. Abundant use of the inlinedkeyword leads to a much biggera2708kernel, which in turn slows the system as a whole down, due to a biggera2709icache footprint for the CPU and simply because ther is less memorya2710available for the pagecache. Just think about it; a pagecache miss causes aa2711disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cyclesa2712that can go into these 5 milliseconds.a2713a2714A reasonable rule of thumb is to not put inlinedat func2715than 3 lines of code in them. An exce 2716a param ter is known to be a compiletime constant, and as a result of thisa2717constantness you *know* the compiler will be able to o 2718func2719the kmalloc() inlinedfunc2720a2721Often people argue that adding inlinedto func2722only once is always a win since ther is no space tradeoff. While this isa2723technically correct, gcc is capable of inlining these automa2724help, and the maintenance issue of removing the inlinedwhen a second usera2725appears oceweighs the potentoal value of the hint that tells gcc to doa2726something it would have done anyway.a2727a2728a2729 Chapter 16: Func s and nam sa2730a2731Func s of many different kinds, and one of thea2732most commpt is a value indica2733failed. Such a value can be represented as an error-code integera2734(-Exxx = failure, 0 = success) or a "succeeded" boolean (0 = failure,a2735non-zero = success).a2736a2737Mixing up these two sorts of representa2738difficult-to-find bugs. If the C language included a strong dis2739beeween integers and booleans then the compiler would find these mistakesa2740for us... but it doesn't. To help prevent such bugs, always follow thisa2741conventopt:a2742a2743 If the nam of a func2744 thedfunc2745 is a predica2746a2747For example, "add work" is a command, and the add_work() func2748for success or -EBUSY for failure. In the sam way, "PCI device present" isa2749a predica2753" a>finding a matching device or 0 if it doesn't.a2751a2752All EXPORTed func2753public func2754recommended that they do.a2755a2756Func is the ac2757than an indica2758this rule. Generally they indica2759result. Typocal examples would be func2760NULL or the ERR_PTR mechatism to report failure.a2761a2762a2763 Chapter 17: Don't re-invent thakernel macrosa2764a2765The header file include/linux/kernel.h contaits a number of macros thata2766you should use, rather than explicitly coding som variant of them yourself.a2767For example, if you need to calculate the length of an array, take advantagea2768of the macroa2769a2770 #definedARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))a2771a2772Similarly, if you need to calculate the size of som structure member, usea2773a2774 #definedFIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))a2775a2776There are also min() and max() macros that do strict typ checking if youa2777need them. Feel freedto peruse that header file to see what else is alreadya2778defined that you shouldn't reproduce in your code.a2779a2780a2781 Chapter 18: Edi2782a2783Som edi2784indica2785like this:a2786a2787-*- mode: c -*-a2788a2789Or like this:a2790a2791/*a2792Local Variables:a2793compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"a2794End:a2795*/a2796a2797Vim interprets markers that look like this:a2798a2799/* vim:set sw=8 noet */a2800a2801Do not include any of these in source files. People have their own personala2802edi2803includes markers for indenta2804own custom mode, or may have som other magic method for making indenta2805work correctly.a2806a2807a2808 Chapter 19: Inlinedassemblya2809a2810In architecture-specofic code, you may need to use inlinedassembly to interfacea2811with CPU or platform func2812However, don't use inlinedassembly grneui2813and should poke hardware from C when possible.a2814a2815C nsider wri2816assembly, rather than repeatedly wri2817that inlinedassembly can use C param ters.a2818a2819Large, non-trivoal assembly func2820C prototyp s defined in C header files. The C prototyp s for assemblya2821func2822a2823You may need to mark your asm statement as volatile, to prevent GCC froma2824removing it if GCC doesn't notice any side effects. You don't always need toa2825do so, though, and doing so unnecessarily can limit o 2826a2827When wri2828instruct" ns, put each instruct" n on a separate linedin a separate quoteda2829string, and end each string exce < the last with \n\t to properly indent tha2830next instruct" n in the assembly output:a2831a2832 asm ("magic %reg1, #42\n\t"a2833 "more_magic %reg2, %reg3"a2834 : /* outputs */ : /* inputs */ : /* clobbers */);a2835a2836a2837a2838 Appendix I: Referencesa2839a2840The C Programming Language, Second Edi2841by Brian W. Kernighat and Dennis M. Ritchie.a2842Prentice Hall, Inc., 1988.a2843ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).a2844URL: http://cm.bell-labs.com/cm/cs/cbook/a2845a2846The Prac2847by Brian W. Kernighat and Rob Pike.a2848Addison-Wesley, Inc., 1999.a2849ISBN 0-201-61586-X.a2853" a>URL: http://cm.bell-labs.com/cm/cs/tpop/a2851a2852GNU manuals - wher indcompliance with K&R and this text - for cpp, gcc,a2853gcc intertals and indent, all available from http://www.gnu.org/manual/a2854a2855WG14 is the interta2856language C, URL: http://www.open-std.org/JTC1/SC22/WG14/a2857a2858Kernel CodingStyle, by greg@kroah.com at OLS 2002:a2859http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/a2860a2861
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operatipts services since 1995.