3

I was trying to call C++ from C. I am not sure about the linking order. It could have been that to cause the error. For some reasons, the compiler complains undefined reference to helloWorld.

Could anyone advise?

main.c:

 #include "example.h"
 #include <stdio.h>
 int main(){
     helloWorld();
     return 0;
 }

example.h:

 #ifndef HEADER_FILE
 #define HEADER_FILE
 #ifdef __cplusplus
     extern "C" {
 #endif
         void helloWorld();
 #ifdef __cplusplus
     }
 #endif
 #endif

example.cpp:

 #include "example.h"
 #include <iostream>
 void helloWorld(){
     std::cout << "Hello World from CPP";
 }
Ursa Major
  • 851
  • 7
  • 25
  • 47
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Ken White Mar 27 '16 at 19:03
  • That should work and I can only assume you aren't linking-in `example.cpp` (`example.o`). – trojanfoe Mar 27 '16 at 19:04

1 Answers1

1

There are two ways to do this. While both work, one is "cleaner" than the other. Side note: As trojanfoe pointed out, you may have left off the .o on the compile/link command.

Here's a two step process:

cc -c main.c
c++ -o mypgm example.cpp main.o

This is a bit ugly because the usual convention is that the source that gets compiled is the one with main

Here's the more usual way:

c++ -c example.cpp
cc -c main.c
c++ -o mypgm main.o example.o

NOTE: In both cases, the "linker" must be c++ to resolve the std::* that example.cpp uses


UPDATE:

What is mypgm?

mypgm [just an example name] is the name of the [fully linked and ready to run] output executable or program. It's the argument for the -o option. The linker takes your relocatable input .o files, links them together to produce the output file [that can now be run as a command].

It's pretty standard nomenclature for something that is arbitrary in example instruction or code sequences [like here on SO]. You could replace "mypgm" with "ursa_majors_test_program" or "example", or whatever you'd like. To run the program, then type ./mypgm [or ./ursa_majors_test_program or ./example]

There's no magic to the name, just like there was no magic to you naming your source files main.c and example.cpp

It should be descriptive of function. If you had said you were working on a text editing program, in my example, I might have used -o editor

Craig Estey
  • 30,627
  • 4
  • 24
  • 48