Haven't used C::B for a while, and now I need to compile a C++ project that also include some old .c/.h files. I have added all the files to the project and included the headers for the functions, but I get an 'undefined reference' error. Am I making some basic mistake?
I have made a small project based on "hello world" that reproduces it. The project files are
test
├── bin
│ └── Debug
├── main.cpp
├── main.hpp
├── obj
│ └── Debug
├── test.c
├── test.cbp
├── test.depend
└── test.h
So to not get the 'undefined reference to print_message(char*)' error I need to make sure that test.c is compiled before main.cpp and linked when main.cpp is compiled?
Thanks for your help.
The build log is
-------------- Build: Debug in test (compiler: GNU GCC Compiler)---------------
g++ -o bin/Debug/test obj/Debug/main.o obj/Debug/test.o
/usr/bin/ld: obj/Debug/main.o: in function `main':
/tmp/test/main.cpp:9: undefined reference to `print_message(char*)'
collect2: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
2 error(s), 0 warning(s) (0 minute(s), 0 second(s))
The contents of main.cpp are
#include <iostream>
#include "main.hpp"
using namespace std;
int main() {
cout << "Hello world!" << endl;
print_message ("Hello world!");
return 0; }
And the files main.hpp, test.h and test.c are:
main.hpp
#ifndef MAIN_HPP_INCLUDED
#define MAIN_HPP_INCLUDED
#include "test.h"
#endif // MAIN_HPP_INCLUDED
test.h
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
void print_message (char *message);
#endif // TEST_H_INCLUDED
test.c
#ifndef TEST_C_INCLUDED
#define TEST_C_INCLUDED
#include <stdio.h>
void print_message (char *message) {
printf("%s\n", message);
}
#endif // TEST_C_INCLUDED
When mixing C and C++ sources you must specify C linkage in the C include files. Try this version of test.h:
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
void print_message (char *message);
#ifdef __cplusplus
} /* end of the 'extern "C"' block */
#endif
#endif // TEST_H_INCLUDED