1

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?

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
akashrajkn
  • 2,295
  • 2
  • 21
  • 47

2 Answers2

5

Replace void checker() with extern "C" void checker in you cpp file to ensure correct linkage (C or cdecl linkage).


Your compilation commands are incorrect, you don't compile header files. Use:

$ g++ RULE_MINE.cpp main.c

And perhaps more flags (-W -Wall -O2 for example)

or

$ g++ -c RULE_MINE.cpp
$ g++ -c main.c # or gcc -c main.c
$ g++ RULE_MINE.o main.o
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • 1
    In fact, you *can* [precompile header files](https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html). – Quentin Apr 27 '15 at 13:58
4

Your implementation needs extern too :

extern "C" void checker()
{
  cout<<"whaaat?"<<endl;
}
Quentin
  • 62,093
  • 7
  • 131
  • 191