can a file other than a .h file be included with #include

Dani AI

Generated

Short answer: yes — the preprocessor literally pastes the contents of the named file into the translation unit, so the filename extension does not change that behavior. was right in principle; see the C preprocessor documentation for how #include performs textual inclusion and how #include "file" differs from #include <file> in search order (cppreference).

That ability is useful for macros, generated snippets, or platform-specific assembler fragments, but including C source files (.c) is rarely the right long-term choice. Including a .c that defines functions or non-static globals merges those definitions into the includer and often produces linker errors or duplicate symbols if used from multiple translation units. The usual, robust pattern is:

  • Put prototypes and extern declarations in a header with include guards.
  • Compile each .c separately and link the object files.
    A minimal header example:
    
    #ifndef MYMODULE_H
    #define MYMODULE_H

int myfunc(int x);
extern int shared_counter;

#endif



If following @Dazaa's approach (dropping .c into other .c with `#include`) causes "multiple definition" or maintenance problems, stop including the .c files, create proper headers, and use your build system to compile/link separately. For more discussion of why including .c is discouraged and practical consequences, see the linked Stack Overflow thread ([why-include-c-files-is-bad](https://stackoverflow.com/questions/474528/why-shouldnt-you-include-c-files)).

Recommended Answers

All 4 Replies

can a file other than a .h file be included with #include

Answer : Yes :)
Any file can be included using #include.. #include just inserts the contents of that file in your C program.

Answer : Yes :)
Any file can be included using #include.. #include just inserts the contents of that file in your C program.

can you give me any program as example, in which we are using #include and a file other than .h extension

can you give me any program as example, in which we are using #include and a file other than .h extension

Lets sayI have a file main.c and helloworld.inc
In main.c I will write

#include "helloworld.inc" //Including a file other than .h

and in
helloworld.inc I will write

#include <stdio.h>

int main()
{
        printf("Hello, World\n");
        return 0;
}

Now compile main.c and run the executable, It will print

Hello, World

yes the program i am working on now starts with:

#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <winsock2.h>
#include "myramdomize_windows2010.c"
#include "CRC_simple_windows.c"

#define WSVERS MAKEWORD(2,0)
WSADATA wsadata;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.