problem with "multiple definition"
Say I have a very little header file like so:
#ifndef A_H_
#define A_H_
void print();
int getInt()
{ //ERROR HERE
return 5;
}
#endif /* A_H_ */
And a source file implementing print like so:
#include "a.h"
void print()
{
printf("%d\n",getInt()); //WARNING HERE
}
And my main() function code:
#include <stdio.h>
#include <stdlib.h>
#include "a.h"
int main(void)
{
print();
return EXIT_SUCCESS;
}
Notice that getInt
is defined in the header file and i开发者_JS百科nvoked in the source file.
When I compile I get multiple definition of
getInt'` in the header file, but I've only
defined it once! The source file (.c) only invokes it. What is my problem?
Thanks
You're probably including your header file into another source file too. You may try to move the definition to the .c file or declare getInt()
as inline
.
You should move getInt()
into a.c, i.e.
a.h:
#ifndef A_H_
#define A_H_
void print(void);
int getInt(void);
#endif /* A_H_ */
a.c:
#include <stdio.h>
#include "a.h"
void print(void)
{
printf("%d\n",getInt());
}
int getInt(void)
{
return 5;
}
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "a.h"
int main(void)
{
print();
return EXIT_SUCCESS;
}
As a rule of thumb, interfaces (i.e. prototypes for externally accessible function, plus related typedefs and constants etc) belong in .h files, while omplementations (i.e. actual function definitions, plus private (static) functions and other internal stuff) belong in .c files.
精彩评论