Although the string literal following the extern keyword in a linkage directive is implementation-dependent, all implementations must support C and C++ string literals. Refer to linkage specifications in The C++ Programming Language, Third Edition for more information.

Differences in Argument Passing Conventions

When your C++ code calls functions written in C, ensure that the called C functions do not use function prototypes that suppress argument widening. If they do, your C++ code passes arguments wider than the expectations of your C code.

The main() Function

When you mix C++ modules with C modules, the overall control of the program must be written in C++. The main function should appear in a C++ module, rather than in a C module. There are two exceptions:

1.C++ programs and libraries, including HP-supplied libraries, without any global class objects containing constructors or destructors.

2.C++ programs and libraries, including HP-supplied libraries, without static objects.

Examples: HP aC++ Calling HP C

The following examples show a C++ program, calling_c.C that calls a C function, get_name. The C++ program contains a main function.

//************************************************************

//This is a C++ program that illustrates calling a function *

//written in C. It calls the get_name() function, which is *

//in the “get_name.c” module. The object modules generated *

// by compiling the

“calling_c.C” module and

by compiling

*

//

the “get_name.c”

module must be linked to

create an

*

//

executable file.

 

 

*

//************************************************************ #include <iostream.h>

#include “string.h” //************************************************************

//declare the external C module extern “C” char* get_name(); class account

{

private:

char* name;

// owner of the account

protected:

 

 

double balance;

//

amount of money in the account

public:

 

 

account(char* c)

//

constructor

{name = new char [strlen(c) +1]; strcpy(name,c);

balance = 0; }

void display()

{cout << name << “ has a balance of “

<<balance << “\n”; }

};

int main()

{

account* my_checking_acct = new account (get_name());

//send a message to my_checking_account to display itself my_checking_acct->display();

}

The following example shows the module get_name.c. This function is called by the C++ program.

/****************************************************/

/* This is

a C function

that is called

by main() in */

/*

a C++ module, “calling_c.C”. The object

*/

/*

modules

generated by

compiling this

module and

*/

190 Mixing C++ with Other Languages

Page 190
Image 190
HP C/aC++ for PA-RISC Software Differences in Argument Passing Conventions, Main Function, Examples HP aC++ Calling HP C