[Search for users] [Overall Top Noters] [List of all Conferences] [Download this site]

Conference turris::c_plus_plus

Title:C++
Notice:Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS)
Moderator:DECCXX::AMARTIN
Created:Fri Nov 06 1987
Last Modified:Thu Jun 05 1997
Last Successful Update:Fri Jun 06 1997
Number of topics:3604
Total number of notes:18242

3574.0. "Referencing C++ variables from C files" by ADCA01::MADHURIA () Fri May 16 1997 12:07

    Hi,


    We are porting an application from Digital Unix to windows NT. The
    application is developed using C, C++, FORTRAN.

    We have some variables defined in C++ files and making use of these 
    variables in our C files.

    For Example,

    C++ code
    --------
    extern "C"  void test();
    int var1;
    main()
    {
       test();
    }

    c code
    ------

    #include <stdio.h>
    extern int var1;
    void test()
    {
        printf ("\n %d",var1);
    }

    During linking these files, the linker gives an unresolved external
    symbol error for the variable var1.

    How to go about solving this problem ?

    Thanks in advance

    -Madhuri
    Digital India

               
T.RTitleUserPersonal
Name
DateLines
3574.1works fine for me.DECC::J_WARDFri May 16 1997 12:5611
I called the first file t.cxx and second file t2.c
and did:

cxx t.cxx t2.c

and it linked just fine.

I think we need more info, what system you are running,
what compiler version, and how you are trying to link
these files...
3574.2GEMEVN::FAIMANDer Mai is gekommen, der Winter is ausFri May 16 1997 13:1214
    We are porting an application from Digital Unix to windows NT. The
    application is developed using C, C++, FORTRAN.

In DEC C++ (Unix and VMS), function names are "mangled" with type information,
but variable names are not.  In MS C++, both function and variable names are
mangled.

This means that if you want to access a variable in both C and C++ code, you
must declare it with extern "C", just as you would do for a function name.

(You can regard this as an error in your C++ code that DEC C++ let you get away
with, but that MS C++ is stricter about.)

	-Neil
3574.3DECCXL::OUELLETTEmudseason into blackfly seasonFri May 16 1997 17:4945
Confiriming Neil's advice...

Change your example as follows:

// C++ code
extern "C" void test();
extern "C" int var1;
main()
{
  test();
}

// c code
#include <stdio.h>
extern int var1;
void test()
{
  printf ("\n %d",var1);
}

Or better:

// header.h
void test();
extern int var1;


// C++ code
extern "C" {
#include "header.h"
}

main()
{
  test();
}

// c code
#include <stdio.h>
#include "header.h"

void test()
{
  printf ("\n %d",var1);
}
3574.4It workedADCA01::MADHURIATue May 20 1997 12:248
    Hi,
    
    I incorporated the change suggested by you and it worked. Thanks a lot
    for your help.
    
    Regards,
    -Madhuri
    (Digital India)