I keep getting a linker error with the following setup.
I have file1.c which contains the following code
#if defined( _TEST_ENABLED )
int get_value()
{
.
.
.
}
#endif /*_TEST_ENABLED */
I have file2.c which includes file2.h, which defines _TEST_ENABLED. file2.c makes a call to get_value(), however the linker isn't having any part of that.
I've exhausted a lot of different options with zero success. Now i'm asking for help :)
如果file1.c不包含file2.h或任何定义_TEST_ENABLED
文件,则当预处理器在file1.c上运行时,将不会定义_TEST_ENABLED
, _TEST_ENABLED
将不会编译int get_value() { ... }
。
In order to call a function in another file:
1) The files must be compiled or at least linked together. The easiest way to do this is gcc file1.c file2.c
, however you can also compile both files to *.o
files and then link together.
2) The calling file must have, usually through an included header, a prototype of the function. This prototype must appear before the function is used. So, if file2.h
defines _TEST_ENABLED
, then you must (in file2.c
) include file2.h
, and then either file2.c
or file2.h
must include file1.h
, which must contain a function prototype ( int get_value;
)
For example:
file1.c
#include <file1.h>
#include <file2.h>
int main() {
get_value();
}
file1.h
#ifndef _FILE2_H
#define _FILE2_H
#define _TEST_ENABLED
#endif
file2.c
#include <file2.h>
#include <file1.h>
#ifdef _TEST_ENABLED
int get_value() {
return 42;
}
#endif
file2.h
#ifndef _FILE2_H
#define _FILE2_H
int get_value();
#endif
Note that for the purposes of the preprocessor, file1.c
and file2.c
are processed completely separately. When processing file2.c
, it MUST find #define _TEST_ENABLED
somewhere, which is why file2.c
must include file1.h
. Since this is getting a little circular, you should add " #include
-guards to each header file, as shown above.
There are some ambiguities in your question, but given the following three files, I can compile and build in ANSI C, but I have to include the .h in both .cs:
file1.c
#include "file2.h"
int main(void)
{
someFunc();
get_value();
return 0;
}
#ifdef _TEST_ENABLED
int get_value(void)
{
return 0;
}
#endif
file2.c
#include "file2.h"
int someFunc(void);
int someFunc(void)
{
get_value();
return 0;
}
file2.h
#define _TEST_ENABLED
int get_value(void);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.