Why can't I define simple C functions in the header file?

I always get a build error when I try to define the C function in the header file just above the class interface.

but when I do the same in the implementation file and advertise in the header. Everything works.

I wanted to know why this is so because I defined the enumerations, structures, constant NSStrings in the header file, so why not C functions?

+8
objective-c
source share
1 answer

This is due to how the C linker (or link editor) works. When the C compiler encounters a function definition, it prepares the assembler code that implements this function and marks it with a symbol that tells the linker to "start a function with this name here." The character is usually called with an underscore followed by the name of the function, for example. _printf .

If you define a function in the header file, then every .c or .m file that imports this header will compile this function and cause the compiler to issue the same character. The compiler expects to find only one instance of each character, so this is an error.

This is not due to the existence of #include security devices or to the use of #import instead of #include . The C compiler works with separate translation units, with the help of which it implies separate source files. Preprocessor strategies stop you, including the same header file, twice in the same source file, but do nothing to coordinate actions across multiple files. This means that he has the right to include the same headers in different source files: it also means that when compiling different files they can (legally) contain the same character.

It is the job of the link editor to combine these files by resolving any references to characters that were unknown at compile time. If you try to link objects (the name of compiled and assembled translation units) that have the same symbol in the same archive, shared library or executable file, then you will get the error message that you see here.

Solutions:

  • Do not define the function in the header, just declare it there and define it in the implementation file; as you already found this to work.
  • Define the function in the header, but include this header in only one place in your code. This is often unacceptable for design reasons.
  • Define the function in the header using the inline modifier. Built-in functions are simply copied by the compiler to the function in which they are called, so the linker symbol is never allocated to them. This has its tradeoffs, which you may wish to read more .
+14
source share

All Articles