3

I'm trying to write a bookstore program, and I'm getting an error saying "multiple definition" in my source code file at my function implementation.

Here is my Book.c file:

#include "Book.h"

void scanBook(book_t* bk) //error here
{
    //implementation here
}

Here is my Book.h file:

#pragma once
#include <stdio.h>

typedef char* str;    
typedef enum Genre {Education, Business, Novel} genre_t;

typedef struct Book{
    str ISBN;
    str title;
    str author;
    float price;
    int quantity;
    genre_t genre;
} book_t;

void scanBook(book_t* bk);

And here is my main.c file:

#include "Book.h"
#include "Book.c"

int main()
{
    return 0;
}

The error occurs at the scanBook function in Book.c but I don't know why, since I included the header file as well as #pragma once, and in the header file I declared the function. It says multiple definition of 'scanBook' and obj\Debug\Book.o .... first defined here.

Any help or clarification would be greatly appreciated!

CassiePray
  • 43
  • 1
  • 1
  • 4

2 Answers2

7

Don’t do:

#include “Book.c"

in your main.c file.

Jeremy
  • 4,339
  • 2
  • 18
  • 12
  • 4
    A little further explanation: When compiling main.c the compiler first includes Book.h. This file contains a prototype of function `void scanBook(book_t* bk);`. That being done the compiler includes Book.c which contains an implementation of `void scanBook(book_t* bk)` which results in an error. Not including Book.c results in compiling main.c successfully with an (yet) unresolved reference to `void scanBook(book_t* bk);`. After compiling Book.c (which contains `void scanBook(book_t* bk);`) the linker merges the compiled object files and resolves the unresolved reference from main.c. – Lukas Thomsen Oct 24 '14 at 19:51
0

the solution is to delete this line:

#include "Book.c"

In C and C++ usually you just include the header files (.h and .hpp), because you give the .c and .cpp files directly to the compiler, so it is ambiguous if you also include them.