0

I have the following scenario,

File 1: main.c

extern void afunction(int);

int main()
{
   afunction(0);
}

File 2: other.cpp

void afunction()
{
   // do some crazy stuff.
   return; 
}

How do I link those two files together so that when the compiler attempts to find afunction() it does?

Note1: I cannot use #include "other.cpp"

Note2: I don't want to create a library unless I have no other choice.

--

I have attempted the following gcc command, but it gives undefined reference.

gcc other.cpp main.c 

Any ideas? Thanks!

Galik
  • 47,303
  • 4
  • 80
  • 117
SFD
  • 565
  • 7
  • 18
  • When mixing C and C++, `main` should be in a *.cpp file. – aschepler Dec 01 '16 at 18:43
  • In `other.cpp` you need to put your function definition in `extern "C" {}` block (or just add `extern "C"` as an additional declarator) so the name is compiled using `C` naming convention. – Galik Dec 01 '16 at 18:45
  • 4
    Those `afunction`'s are not the same. One takes 1 param, the other takes 0 params. Name mangling would disambiguate the two functions, thus the linker will never find `afunction(int)`. – PaulMcKenzie Dec 01 '16 at 18:46
  • Also this may be of use: https://stackoverflow.com/questions/31903005/how-to-mix-c-and-c-correctly/31903685#31903685 – Galik Dec 01 '16 at 18:49
  • @OP Even if it's `C`, you really want to get into the weeds of not matching prototypes? That is why `C` introduced prototypes later on after the initial `C` language took hold, so that programmers didn't need to make these mistakes and spend hours debugging faulty code. – PaulMcKenzie Dec 01 '16 at 18:51
  • Is the mix of `c` and `c++` on purpose? – Support Ukraine Dec 01 '16 at 18:52
  • Even if it's all `C` and no C++, the code above, at least in my eyes, would cause undefined behavior if `afunction` were called due to the mismatched prototype. – PaulMcKenzie Dec 01 '16 at 18:54
  • I ma happy with renaming both too, cpp, the focus of my question is how do I use the extern to bypass having to include a file – SFD Dec 02 '16 at 10:00

1 Answers1

1

Rename main.c to main.cpp

New file, other.h

#ifndef other_H
#define other_H


void afunction();

#endif

Then add the #include in your main.cpp

#include "other.h"

int main()
{
   afunction();
}

Note that it is important that the declaration and definition of afunction() matches, hence the extra header file. When working on something complex enough to be in two files, always add the header file with function declaration, or switch to another language. This is how c/c++ is intended to work for over 25 years.

Bamaco
  • 592
  • 9
  • 25
  • I dont want to use a header file, this was started in the question. – SFD Dec 02 '16 at 09:59
  • @SDF, the question you asked specified you dont want to include the .cpp file. This is standard, never include a .cpp file! But also, always include the .h file. – Bamaco Dec 02 '16 at 15:41