0

I have a test.c file which contains main() function and some test cases and it cannot be modified it(such as adding "include *.h"). Then I have a foo.c file which contains some functions(no main() function). These functions will be tested through test cases in test.c file. What I'm going to do is use foo.c as a library and link it to test.c file. And here is the simple code.

test.c

//cannot modify int main(){ ... bar(); ... } 

foo.c

#include "foo.h" //I will explain this below. int bar(){ ... } 

I'm trying to implement an interface using .h file, such as

foo.h

#ifndef _FOO_H_ #define _FOO_H_ extern int bar(); #endif 

Then using cmd line

gcc -c foo.c gcc -o output test.c foo.o ./output 

You may guess the result. There is a warning that "implicit declaration of function 'bar' is invalid in C99 [-Wimplicit-function-declaration]". And the test.c file cannot run correctly.

Could someone help me about this? Thank you so much!

2
  • 1
    What the heck is main.c? Commented May 2, 2016 at 2:27
  • sry, it's a typo. It should be test.c. I have corrected it Commented May 2, 2016 at 2:29

2 Answers 2

1

Your problem is:

  1. test.c has a call to bar() in it.
  2. test.c doesn't have any declaration for bar, nor does it have an #include for a .h file that declares bar.
  3. You are not allowed to change test.c in any way to add either a declaration or an #include.

This is a hard problem. The C language requires there be a prototype/declaration for bar in test.c! It can be written directly in the test.c file (write extern int bar(); before you call it), or the declaration can come in from another file with an #include statement, but you must have it.

Luckily, GCC has a way to force an #include statement into a file while it's compiling the file. You don't have to change test.c in order to make it start with #include "foo.h". This will solve your problem:

gcc -c -include foo.h test.c 
Sign up to request clarification or add additional context in comments.

1 Comment

Many people do not think about that one
0

You need to include the declaration of bar in the test.c file:

#include "foo.h" 

So that the compiler have the prototype in the translation unit, of test.c.

3 Comments

As I said above, test.c file cannot be modified.
@AATRSong The warning is because test.c called a function that it does not know its prototype. The only way is add it to test.c. "test.c cannot be modified" sounds a weird restriction, can you tell me why?
You assume I don't understand the warning? Good Job. Listen, the test file isn't implement by me. The person who have the test file just use it to test the foo.c file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.