#ifndef in c file?

前端 未结 2 986
一整个雨季
一整个雨季 2021-01-22 21:49

Is it possible to put #ifndef at the top of a c file? Basically I need to check whether a certain preprocessor constant was declared when running the program and my

相关标签:
2条回答
  • 2021-01-22 22:10

    There is a typo in your Makefile since $(CLAGS) should be $(CFLAGS). Learn a lot more about make, notably by running make -p which shows you the many built-in rules to make and use them (e.g. consider using $(COMPILE.c) and $(LINK.c) etc..)

    Don't forget to add -Wall to your CFLAGS, because you want all the warnings from the compiler. You probably want debugging information too, so add g also.

    On Linux, I do recommend using remake for debugging Makefile-s by running remake -x which helps a lot.

    Standard practices are:

    • avoid passing -include to gcc, instead, add a#include "res.h" near the beginning of relevant *.c source files

    • glue the -D to the defined symbol, e.g. -DDESCENDING_ORDER=1

    • add in your Makefile the dependencies on relevant object files to the newly #include-d file res.h; notice that these dependencies could be automatically generated (by passing e.g. -MD to gcc, etc etc...)

    • pass the -DDESCENDING_ORDER=1 thru CFLAGS or better CPPFLAGS

    Don't forget that the order of program arguments to gcc matters a lot.

    addenda

    You may want to generate the preprocessed form res.i of your source code res.c using gcc -C -E and you could have a rule like

      res.i: res.c res.h
               $(CC) -C -E $(CFLAGS) $(CPPFLAGS) $^ -o $@
    

    then do make res.i and examine with some editor or pager (perhaps less) the preprocessor output res.i ; alternatively, do that on the command line

      gcc -C -E -I. -DDESCENDING_ORDER=1  res.c | less
    

    you could remove the generated line information and do

      gcc -C -E -I. -DDESCENDING_ORDER=1  res.c | grep -v '^#' > res_.i
      gcc -Wall -c res_.i
    

    The point is that the preprocessing in C is a textual operation, and your preprocessed form is wrong.

    BTW very recent Clang/LLVM (version 3.2) or GCC (just released version 4.8) compilers give you much better messages regarding preprocessing.

    0 讨论(0)
  • 2021-01-22 22:21

    The code is fine. The error you're getting when using a Makefile has to do with something else (it's hard to be sure without seeing what comes before the #ifndef and seeing the Makefile).

    0 讨论(0)
提交回复
热议问题