saurabh
saurabh

Reputation: 17

Using char in different files in C

I have 3 .c files main.c, fun1.c, fun2.c

char buff[50];//in fun1.c

char *arg;  //in fun2.c

arg = strstr(buff, "001"); //in fun2.c

I want to print buff in fun2.c but it gives an error buff undeclared, even though I declared it in fun1.h as extern char buff[]; There are functions in fun1.c and fun2.c each

Upvotes: 0

Views: 104

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

It is hard to say what is wrong with your particular program, but here is an example which links 2 .c files with one .h file.

1. A header file functions.h:

#include <stdio.h>

extern void func();

Where I use extern to provide definitions for another file.

2. Now, a functions.c file which uses this header file:

#include "functions.h"

void func() {
    printf("hello");
}

This needs to #include the header file, and use the function void() to print a message.

3. Finally, a main.c file which links it all together:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"

int main(void) {
    func();
    return 0;
}

Which also needs function.h as it uses func(). You then can compile the code as:

gcc -Wall -Wextra -g main.c functions.c -o main

You could also look into makefiles, which would reduce this long compilation line to simply make.

Upvotes: 1

Related Questions