Hi..
I'm trying to write a simple program to include a c file in another one..
TEST1.c
#include<stdio.h>
#include<conio.h>
#include<test.c>
void main()
{
printf("%c" str);
getch();
}

test.c
#include<stdio.h>
#include<conio.h>
extern char str;
void main()
{
str='A';
}


Is somethin like this is possible??? Code didn't run successfully

Dani AI

Generated

Short version: including a .c file with #include just pastes that file into the current translation unit and commonly produces duplicate symbols (for example two main functions). was correct to steer you toward separating declarations into headers and definitions into one .c file. Below is a simple, safe pattern to share a variable or function between files.

Example layout (three files):

/* shared.h */
#ifndef SHARED_H
#define SHARED_H

extern char shared_char;
void init_shared(void);

#endif
/* shared.c */
#include "shared.h"

char shared_char = 'A';

void init_shared(void) { /* optional runtime init */ }
/* main.c */
#include <stdio.h>
#include "shared.h"

int main(void) {
    printf("%c\n", shared_char);
    return 0;
}

Compile and link in one step:

gcc main.c shared.c -o app

Or compile separately and link:

gcc -c shared.c
gcc -c main.c
gcc shared.o main.o -o app

Troubleshooting tips: put only extern declarations in headers, and place a single definition in one .c file; missing extern or defining the variable in the header and including it in multiple files causes "multiple definition" linker errors. Use include guards in headers. Prefer int main(void) and return a value. For pausing or simple input use standard I/O (getchar) rather than compiler-specific headers. For formal details on linkage and extern, see the C language reference on linkage: . This pattern should resolve the errors you saw; thanks to for the pointers and to for the example that revealed the problem.

Recommended Answers

All 2 Replies

You'd have multiple definitions of main, which is an error.

A few other points:
- main's return type should be int.
- you should never include .c files. The compiler will create object files (.o or .obj, possibly others depending) and then the linker will put the pieces together. However, functions and structs should be declared (but not necessarily defined) in .h files, which you should #include as needed.
- Try to avoid using conio.h and the functions therein. They are not available with most compilers and hence other people cannot run your code as is. Look into input methods with the standard I/O libraries.

Thanks for ur reply....

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.