I found a tutorial of how to link object files:
I have 3 different files.
main.c

#include<stdio.h>
#include"reciprocal.hpp"
int main (int argc, char **argv)
{
  int i;
  i = atoi (argv[1]);
  printf ("The reciprocal of %d is %g\n", i, reciprocal (i));
  return 0;
}

reciprocal.cpp

#include<cassert>
#include"reciprocal.hpp"
using namespace std;
double reciprocal(int i)
{
    //I should be non-zero.
    assert(i!=0);
    return 1.0/i;
}

reciprocal.hpp

#ifdef __cplusplus
extern “C” {
#endif
extern  double reciprocal (int i);
#ifdef __cplusplus
}
#endif

I compiled and made object code of main.c by command gcc -c main.c -o main.o and it compiled fine but when I'm trying to make object file of reciprocal.cpp by command g++ -c reciprocal.cpp -o reciprocal.o it gave following error:

$ g++ -c reciprocal.cpp -o reciprocal.o
In file included from reciprocal.cpp:2:
reciprocal.hpp:2: error: stray ‘\342’ in program
reciprocal.hpp:2: error: stray ‘\200’ in program
reciprocal.hpp:2: error: stray ‘\234’ in program
reciprocal.hpp:2: error: stray ‘\342’ in program
reciprocal.hpp:2: error: stray ‘\200’ in program
reciprocal.hpp:2: error: stray ‘\235’ in program
reciprocal.hpp:2: error: ISO C++ forbids declaration of ‘C’ with no type
reciprocal.hpp:2: warning: ‘C’ initialized and declared ‘extern’
reciprocal.hpp:2: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
reciprocal.hpp:4: error: expected primary-expression before ‘extern’
reciprocal.hpp:4: error: expected ‘}’ before ‘extern’
reciprocal.hpp:4: error: expected ‘,’ or ‘;’ before ‘extern’
reciprocal.hpp:6: error: expected declaration before ‘}’ token

I'm using Linux-ubuntu 9.10 OS

Edited 6 Years Ago by Blue$kull: n/a

Since this is a c++ forum, I'll give a c++ example (I don't know anything about that extern c stuff!)
main.cpp

#include "test.h"

int main()
{
  Test a;
  a.foo();

  return 0;
}

test.h

#ifndef test_h
#define test_h

#include <iostream>

class Test
{
  public:
    void foo();
};

#endif

test.cpp

#include "test.h"

void Test::foo()
{
  std::cout << "working" << std::endl;
}
g++ -c test.cpp -o test.o
g++ main.cpp test.o -o main

Dave

reciprocal.hpp

extern “C” {

That should be

extern "C" {

Shift-2 not whatever it is you have put in there.

This article has been dead for over six months. Start a new discussion instead.