Jake Brown
Jake Brown

Reputation: 13

Linking error when Calling a C header file

I am calling a C function from a header file I wrote in Qt written in Cpp. I keep getting a linking error when I try to compile my Qt Application.

here is the header file:

#ifndef GROUND_SERVER_H
#define GROUND_SERVER_H


#ifdef __cplusplus
extern "C" {
#endif

struct system_info{
    char id[33];
};

/*  Support function for the below function */
    void Generate_Key(char*,char*,char*);

/*  Runs the actual key generation as well as 
    moves the file to the respectful card or
    USB drive inserted in the system that will
    act as the user system key  */ 
void run_key_generation(struct system_info*,char*,char*);

/*  Function to run the server on a selected 
    port at which the medium that the server 
    is to listen on will be connected.  */
void run_server(unsigned short);

void generate_id();

#ifdef __cplusplus
};
#endif


#endif

Upvotes: 0

Views: 1899

Answers (1)

Daniel Jour
Daniel Jour

Reputation: 16156

#include "foo.h" is only the textual inclusion of the contents of foo.h into the current compilation unit. If you implement a function in a different file, then you need to compile that file, too, and link the resulting object files to form an executable (or library).

This does also apply when mixing C and C++ (or most other compiled) code: You compile the source code files with the compiler suitable for the language they're written in, and finally link everything together.

So:

foo.h

#ifndef FOO_H
#define FOO_H 1
#ifdef __cplusplus
extern "C" {
#endif

int answer(void);

#ifdef __cplusplus
}
#endif
#endif

foo.c

int answer(void) {
  return 42;
}

bar.cc

#include <iostream>
#include "foo.h"

int main(int argc, char ** argv) {
  std::cout << "The answer is " << answer() << std::endl;
  return 0;
}

To create an executable from these files, you need to:

gcc -c foo.c   # Compile C file
g++ -c bar.cc  # Compile C++ file
g++ -o foobar foo.o bar.o # Link

Upvotes: 1

Related Questions