简体   繁体   中英

wrapper function in throwing error “ as ‘p’ was not declared in this scop”

I am trying to access C++ function (f1) and string a from c file using a wrapper function. Code below.

Error thrown is

Error : error: 'p' was not declared in this scope double d = f11( p,i);

1.h

double f11(struct c* p, int i);

1.cpp

#include<iostream>
using namespace std; 
class c
{
    public:   double f1(int i)  // how can i access from c 
    {
        cout<<"I am in c++";
    }
    public : string a;   // how can i access string from c
};

extern "C"  double f11(c* p, int i) // wrapper function
{
    return p->f1(i);
}

2.c

#include<stdio.h>
#include "1.h"
int main()
{
    int i=9;
    double d = f11( p,i);
}

If you manually include the contents of "1.h" in main.cpp, it would look:

#include <stdio.h>

double f11(struct c* p, int i);

int main()
{
    int i=9;
    double d = f11( p,i);
}

There are several problems there.

  1. You haven't declared p before using it in the call to f11 .

  2. You don't have any way of constructing an object of type struct c in main . Even if you were to fix the compiler errors by providing declarations of struct c and p , you'll run into run time problems since the only way to initialize p will be to initialize it to NULL. That wouldn't do you any good since you have a line

     return p->f1(i); 

    in f11 .

  3. Your declaration and definition of f11 will result in linker error. If you want to implement the function as extern "C" , you'll also have to declare it as extern "C" .

     extern "C" double f11(c* p, int i); 
  4. In 1.cpp, the member function f1 does not return a double. That is cause for undefined error, if the compiler does not report that as an error.

See working code at http://ideone.com/aVFWFJ . Please note that I changed the implementation of c::f1 so it does not crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM