HP C/aC++ for PA-RISC Software manual Differences in Argument Passing Conventions, Main Function

Page 190

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

Image 190
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Copyright Notice and Identification Pragmas Pragma Directives and AttributesInitialization and Termination Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Using HP aC++ Templates 132 Standardizing Your Code 138Optimizing HP aC++ Programs 156 Exception Handling 161Tools and Libraries 175 170Mixing C++ with Other Languages 188 Migrating from HP C++ cfront to HP aC++ 198 Distributing Your C++ Products 195Strings 194 Arrays Files in Fortran Documentation feedback 221 Diagnostic Messages 222 Glossary 223 Index 227HP secure development lifecycle Intended Audience About This DocumentWhat’s in This Document Typographical Conventions This document uses the following conventionsHP-UX Release Name and Release Identifier Publishing HistoryRelated Documents HP-UX 11i ReleasesHP Encourages Your Comments Following is a list of documents available with this releaseC89 C99 ecom Ctcom Getting Started with HP aC++Components of the Compilation System Other HP aC++ executable files areExecuting the Program Using the aCC CommandCompiling a Simple Program Debugging ProgramsCompiler Command Syntax and Environmental Variables Examples of the aCC Command++ Source File .C file Files on the aCC Command LineAssembly Language Source Files .s Files Preprocessed Source Files .i FilesObject Files .o Files Configuration Files .conf FilesEnvironment Variables Library Files .a and .so FilesCxxopts Environment Variable ACCFULLPATHNAMES Environment VariableACCMAXERR Environment Variable Cclibdir Environment VariableCcrootdir Environment Variable ACC -L/mnt/proj/lib file.o ACC file.oTmpdir Environment Variable Floating InstallationCxxmapfile Environment Variable Export CCROOTDIR=/mnt/CXX2.1Setting up Floating Installation HP aC++Command-Line Options ACC +DO11.22 +O3 app.C Options to Control Code GenerationACC -c sub.C prog.C ILP32 Data Model and LP64 Data ModelUsing +DS to Specify Instruction Scheduling Compiling in Networked EnvironmentsACC -S prog.C Data Alignment and StorageSize and Alignment of HP Compiler Data Types +expandtypesindiag Debugging OptionsFshort-enums ACC +u1 app.CG1 Algorithm When to use -g, -g0, and -g1Differences Between -g, -g0, and -g1 Options +macrodebug+pathtrace=kind +noobjdebug+pathtrace Local+pathtrace=globallocal Error HandlingNone ACC +p file.C+Wargs +wn+Wcontextlimit +Weargs +wperfadvice+We +Wv+wsecurity Exception HandlingExtensions to the Language +noehFloating-Point Processing Options +Onofenvaccess+Onocxlimitedrange Nofpwidetypes FpevalFpevaldec +decfp+Oprefetchlatency +FPmode+Onolibmerrno +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs Online Help Option +helpInlining Options +inlinelevel numExec Library OptionsDynamic Lname+nostl Linker OptionsMinshared +Onolibcalls=+Onodynopt UsymbolUsymbol +Onodynopt+ild Options for Naming the Output FileNative Language Support Option +ildrelinkBasic Optimization Level Options Handling Null Pointers OptionsCode Optimizing Options ACC -z file.C+O2 +O0+O1 +O3ACC +O3 prog.C Additional Optimization Options for Finer Control+O4 +O4+nonrv Ipo+Onofailsafe +Onolimit Advanced +Ooptimization Options+Onoaggressive +Onoptrstoglobals=list+Onodataprefetch +Onocrossregionaddressing+Onodatalayout +Onofltacc+Ofrequentlycalled +Onoinitcheck+Olit +Onoinline+Ointegeroverflow +Onoloopunroll +Olevel+Onolooptransform +Onoopenmp+Onoparmsoverlap +opts+Onoparminit +Onoprocelim+Onosignedpointers +Orarelycalled+Oshortdata +Onostoreordering +OtypesafetyProfile-Based Optimization Options +OunrollfactorDisplaying Optimization Information Parallel Processing OptionsInformation Embedding Options Annotate=structsOption Matrix for -mt Required if -DPOSIXCSOURCEis used+Onoautopar +tls=staticdynamicFast Performance Options+wlock +Ofast+nosrcpos +Ofaster+Onotlscallschangetp +DSmodel+ub Porting Options+sb +uc+wendian +w64bit+wdriver This warning can be suppressed by adding an extra castDname Preprocessor OptionsRedirecting Output From This Option +maked Maked+Maked ExamplesUname Profiling Code Options+profilebucketsize +check=all Runtime Checking Options+check +check=none+check=boundsarray +check=boundspointer Compiling with +check=boundspointerCheck off by one out-of-bounds access Check off by any number out-of-bounds access+check=globals +check=lock+check=malloc +check=stackframevariablesnone +check=threadCh = intval & 0xff +check=truncateexplicit +check=truncateexplicitimplicit+check=uninit +check=truncateimplicitAarm Standards Related OptionsAarm Ag++ AC89AC99 Agcc+legacycpp AOa and -AOe+legacyv5 +std=c89c99c++98c++11gccg++gnu +stl=rwnoneWc,-koeniglookup,onoff +tru64Wc,-ansiforscope,onoff +tru64More Examples of -t Subprocesses of the CompilerTx,name Tx,nameWx,args Bextern Symbol Binding OptionsBdefault Passing Options to the Linker with -WBprotected BhiddenBhiddendef BprotecteddataTemplate Options Trigraph Processing Suppression Option +instincludesuffixesVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r ACC -V app.C Concatenating OptionsACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Pragma Directives and Attributes Initialization and Termination PragmasCopyright Notice and Identification Pragmas #pragma Versionid Software Product, Version 12345.A.01.05 Data Alignment Pragmas#pragma Versionid string #pragma align NData Alignment Pragmas Basic Example Template ExampleImplicit Access to Unaligned Data Handling Unaligned Data#pragma unalign Typedef T1 T2 Interaction between pack and unalign pragmas is as followsOptimize Pragma Optimization PragmasOptlevel Pragma Floattrapson PragmaNoinline Pragma Diagnostic Pragmas Other PragmasEstimatedfrequency Pragma Defaultbinding PragmaBinding Pragma Extern PragmaHpdefinedexternal Pragma Hdrstop PragmaHidden Pragma Hpdefinedinternal PragmaProtected Pragma POP PragmaPragma once Ptrsstronglytyped PragmaStdc FLOATCONSTDECIMAL64 Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc Cxlimitedrange Pragma Stdc Fpcontract PragmaUnrollfactor Pragma Stdc Fenvaccess PragmaOMP Atomic Pragma OMP for Pragma OMP Barrier PragmaOMP Critical Pragma OMP Flush PragmaOMP Parallel Pragma OMP Master PragmaOMP Ordered Pragma OMP Parallel for PragmaOMP Single Pragma OMP Parallel Sections PragmaOMP Sections Pragma OMP Task PragmaOpenMP Clauses Shared DefaultCopyprivate CopyinAttributes Attribute nonexposing Attribute nonexposingAttribute noreturn Attribute noreturnAttribute visibility Attribute formatAttribute warnunusedresult Syntax Preprocessing DirectivesOverview of the Preprocessor Usage GuidelinesDescription Source File Inclusion #include, #includenextSyntax Assertions #assert, #unassertExamples Macro Replacement #define, #undef#define mac very very long\ Replacement string Macros with ParametersExample Specifying String Literals with the # OperatorConcatenating Tokens with the ## Operator Following illustrates the ## operatorVar1 is Using Macros to Define ConstantsOther Macros #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Assertions #assert, #unassert Predefined MacrosHP aC++ predefines the following predicates Conditional Compilation #if, #ifdef, .. #endifCode that compiles if the expression evaluates to zero Using the #ifdef and #ifndef Directives Using the defined OperatorUsing the #if Directive Using the #else DirectiveExample Line Control #line#line 5 myfile Pragma Directive #pragma and Pragma Operator This macro enables the following non-standard featuresIostream Performance Improvement Pragma See page 96 for more information on pragmasExamples Error Directive #errorTrigraph Sequences Line below contains the trigraph sequence ??=When this line is compiled it becomes ??=line 5 myfileScope and Precedence Using HP aC++ TemplatesInvoking Compile-Time Instantiation Template ProcessingPerformance Explicit InstantiationUsage Template class TablecharFunction Template Command-Line Option InstantiationCompile-Time Instantiation ACC -c +instcompiletime a.C ACC -c a.CPossible Duplicate Symbols in Archive Libraries Why Use Compile-Time InstantiationPossible Duplicate Symbols in Shared Libraries ScopeBuilding an Archive Library with +instauto/+instclose ++ Template TutorialClass Templates Building an Archive Library with Compile-time InstantiationFunction Templates Bool Keyword Standardizing Your CodeHP aC++ Keywords HP aC++ KeywordsCompile time error message is Dynamiccast KeywordAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Namespace and using Keywords Connections Across Translation UnitsAn Auxiliary Translation Unit Using- declarations and using- directivesUsing Nx // Where N is a namespace, x is a name in N IntPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Template Keyword Wchart KeywordTypename Keyword Use it as the name of the template C below Overloading new and delete for ArraysDeclare a class as a member of the class template C2 below Example Standard Exception Classes RangeerrorInvalidargument Typeinfo Class Exceptions Thrown by the Standard C++ LibraryFollowing exceptions are thrown by the Standard C++ Library Unsupported Functionality Int before const typeinfo& constMemfun1reft Memfunreft Iostream Requesting Optimization Setting Basic Optimization LevelsOptimizing HP aC++ Programs Level 1 OptimizationLevel 4 Optimization Additional Options for Finer ControlLevel 3 Optimization Enabling Aggressive OptimizationsEnabling Only Conservative Optimizations Removing Compilation Time Limits When OptimizingProfile-Based Optimization Limiting the Size of Optimized CodeMaintaining Profile Data Files InstrumentationCollecting Data for Profiling Sample.exe input.file1 Sample.exe input.file2ACC -o sample.exe +Oprofile=use +O3 sample.C Pragmas That Control OptimizationPerforming Profile-Based Optimization See Optimization Pragmas page 103 for more informationException Handling Exception Handling in C++Basic Exception Handling Example Function Try Block ExamplesDebugging Exception Handling Performance Considerations Using ThreadsUsing Locks Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library 1.2.1 and Tools.h++ Required Command-line OptionsRogue Wave Standard C++ Library LpthreadThis option applies only to kernel threadsLimitations Using -DTHREADSAFE with the cfront Compatible libstreamUsing -DHPACCTHREADSAFERBTREE Cout endlException Handling Pthreads Posix ThreadsACC -mt prog.c Function Scoping Parallel Programming Using OpenMPOpenMP Implementation OpenMP Library OpenMP Header FileOpenMP APIs are defined in the library libomp Openmp Macro +Onoopenmp Command Line OptionEnvironment Variables in OpenMP Where, kind is either of of static, dynamic, or guidedExport OMPDYNAMIC=value Setenv Ompdynamic value Runtime Library Functions in OpenMPExecution Environment Functions Export OMPNESTED=value Setenv Ompnested valueOmpgetmaxthreads OmpsetnumthreadsOmpgetnumthreads OmpgetthreadnumOmpgetdynamic Lock FunctionsOmpsetdynamic OmpsetnestedOmpsetlock and ompsetnestlock Ompinitlock and ompinitnestlockOmpdestroylock and ompdestroynestlock Ompunsetlock and ompunsetnestlockOmpgetwtime Timing FunctionsOmptestlock and omptestnestlock Functions OmpgetwtickTools and Libraries HP Specific Features of lex and yaccCreating and Using Libraries Locale directive for lexStandard C++ Library Introduction to Using the Standard C++ LibraryHP aC++ Libraries IntroductionDifferences between Standard C++ Library and Other Libraries Non-Object-Oriented Design of the Standard C++ LibraryStandard C++ Library Reference Incompatibilities Between the Library and the StandardHP aC++ Runtime Support Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cTools.h++ Library IOStream LibraryLinking with Shared or Archive Libraries Creating and Using Shared LibrariesLinking to C++ Libraries Specifying Other LibrariesCreating a Shared Library Using a Shared LibraryExample of Creating and Using a Shared Library Linking Archive or Shared LibrariesForcing the Export of Symbols in main Advanced Shared Library FeaturesUpdating a Shared Library Routines and Options to Manage C++ Shared Libraries Binding TimesSide Effects of C++ Shared Libraries Linker Options to Manage Shared LibrariesStandard HP-UX Libraries and Header Files Allocation Policies for ContainersFor -AA Standard Library For a string typeHP aC++ File Locations HP aC++ Executable FilesUsr/lib/hpux##/libCsup.so HP aC++ Runtime Libraries and Header FilesUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant Calling Other Languages Mixing C++ with Other LanguagesData Compatibility between C and C++ Syntax of extern C Using the extern C Linkage SpecificationHP aC++ Calling HP C Examples of extern CMain Function Differences in Argument Passing ConventionsExamples HP aC++ Calling HP C Running the Example HP C Calling HP aC++Enter the nameJoann Joann has a balance To compile the example, run the following commands Compiling and Running the Sample ProgramsFunction Naming Conventions Using Reference Variables to Pass ArgumentsCalling HP Fortran 90 from HP aC++ Example of Reference Variables as ArgumentsArrays Using extern C LinkageStrings Files in FortranDistributing Your C++ Products Applications that use HP aC++ Shared LibrariesLinking Your HP aC++ Libraries with Other Languages Installing your ApplicationHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files Getting Started with Migration Migrating from HP C++ cfront to HP aC++General Guidelines for Migration CC +p cfrontfile.CWriting Code for both Compilers Command-Line DifferencesNew Command-Line Options Explicit Loading and Unloading of Shared LibrariesObsolete Command-Line Options Describes obsolete command-line options for HP aC++Changed Command-Line Options PtvException Handling is the Default Migration Considerations when DebuggingMigration Considerations when Using Exception Handling See Debugging Options page 35 for complete informationPossible Differences when Exiting a Signal Handler Memory Allocation Failure and operator newDifferences in setjmp/longjmp Behavior Calling unexpectedUnreachable catch Clauses Throwing an Object having an Ambiguous Base ClassMigration Considerations when Using Libraries Standards Based LibrariesManip3C++ iostream manipulators HP C++ cfront Compatibility LibrariesFstream3C++ iostream and streambuf specialized to files Man 3s filebufHP C++ cfront Task Library Not Supported Migration Considerations Related to PreprocessingHP C++ cfront Complex Library Not Supported Replace #include with complexChanges in C++ Semantics Migration Considerations Related to StandardizationObsolete Preprocessor Options Implicit Typing of Character String LiteralsOverload Resolution Ambiguity of Subscripting Operator Execution Order of Static Constructors in Shared LibrariesMore Frequent Inlining of Inline Code Changes in C++ SyntaxExplicit int Declaration Equivalent, valid HP aC++ code follows For Statement, New Scoping RulesStruct as Template Type Parameter is Permitted WC,-ansiforscope,onTokens after #endif This code compiles without error with HP aC++Base Template Class Reference Syntax Change Overload not a KeywordStatic Member Definition Required Dangling Comma in enumDeclaring friend Classes Duplicate Formal Argument Names Using in Class DefinitionsIncorrect Syntax for Calls to operator new Ambiguous Function or Object DeclarationOverloaded Operations ++ Reference InitializationCompiling this code HP aC++ generates the following error Using operator new to Allocate ArraysOn HP aC++, the following error is generated Parentheses in Static Member Initialization ListQualified-id Required in Static Member Initialization List Non-constant Reference InitializationDigraph White Space Separators Migration Considerations when Using TemplatesVerbose Template Processing Information CA aCommon Template Migration Syntax Changes Converting Directed Mode to Explicit InstantiationCfront Implicit Include Convention Documentation feedback AC++ Message Catalog Diagnostic MessagesFrequently Encountered Messages Glossary AggressiveInternational Standard defines only synchronous exceptions See template Glossary Symbols IndexCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb