lundi 27 avril 2015

Calling C++ function from a C file gives an "undefined reference" compiler error

I have the following files - main.c, RULE_MINE.h and RULE_MINE.cpp

main.c

#include "RULE_MINE.h"
int main()
{
  checker();
}

RULE_MINE.h

#ifndef HEADER_FILE
#define HEADER_FILE

#ifdef __cplusplus

extern "C"
{

#endif

//declare functions here
  void checker();

#ifdef __cplusplus

}

#endif

#endif

and RULE_MINE.cpp

#include <bits/stdc++.h>
#include "RULE_MINE.h"

using namespace std;

void checker()
{
  cout<<"whaaat?"<<endl;
}

I am compiling the following way

$ g++ RULE_MINE.h
$ g++ -c RULE_MINE.cpp
$ g++ main.c

For this, I get a compiler error

main.c:(.text+0x1947): undefined reference to 'checker'
collect2: error: ld returned 1 exit

I am unable to find what the error is. But suppose in the main.c file if I include #include "RULE_MINE.cpp" , then it is running properly and gives an output. Can you please explain why I am getting this error?

Aucun commentaire:

Enregistrer un commentaire