Initialize a global with a global from another file

hi,
I know that initialization order for global variables across compilation units is not defined, but if I have
file1.cpp
  int x0 = 33, x1 = 55;
  extern int y0, y1;
  static int a[] = { y0, y1 };
  void print_a( void ) { printf( "\na[0] = %d\na[1] = %d", a[0], a[1] ); }
  extern void print_b( void );
  main()
    print_a();
    print_b();
and file2.cpp
  int y0 = 77, y1 = 99;
  extern int x0, x1;
  static int b[] = { x0, x1 };
  void print_b( void ) { printf( "\nb[0] = %d\nb[1] = %d", b[0], b[1] ); }
I notice that values are displayed correctly and consequently, initialized in the order I need. So what's the secret, coincidence, am I lucky? Does it make any difference if file2.cpp is part of a static library?
Thanks

@ Igor Tandetnik: Yes, I chose an example with circular dependency just to show that it was not the situation that, by luck, the "other" file was was initialized first. Yes, I would like a solution for such circular dependency, but I hope that I will
find, at least, a solution for the case when such circular dependency does not exist. What I want to achieve? As the title says, I want a solution to be able to initialize globals with globals from another file, a solution as general and fault proof and convenient
as possible.
@ Wyck: I thought about something like that, problem is that in case of large arrays there is a lot to type. Another solution (it saves a little typing) I saw was something like
// common_header.h
#define LIST_A  y0, y1
#define LIST_B  x0, x1
// file1.cpp
#include "common_header.h"
Number x0(33), x1(55);
static Number a[] = { LIST_A };  // just to give correct size
// file2.cpp
#include "common_header.h"
Number y0(77), y1(99);
static Number b[] = { LIST_B }; // just to give correct size
// init.cpp
extern Number LIST_A, LIST_B;
void init()
{  Number a_[] = { LIST_A };   Number b_[] = { LIST_B }; // stack usage
   for( int i = 0; i <_countof( a_ ); i++ )  a[ i ] = a_[ i ];
   for( int i = 0; i <_countof( b_ ); i++ )  b[ i ] = b_[ i ];
This still has the problem of using much stack in case of large arrays and if array members are more complex structures (might also contain string literals), there is a bit more difficult.
Bellow is a solution I came up with using macros but which I don't really like because is a bit cumbersome. I'm looking for something better/more elegant/safer or simply I want to see what other solutions people see here.
// file1.cpp -------------------------------------------
#define MEMBER_LIST( Usage ) \
Usage( x1 ) \
Usage( x2 )
#define IMPORT( ext_member ) extern Number ext_member;
#define COUNT( member ) 1 +
#define LOAD( member_val ) a[ i++ ] = member_val;
Number y1 = 77, y2 = 99;
MEMBER_LIST( IMPORT )
static Number a[ MEMBER_LIST( COUNT ) 0 ];
static void InitGlobals_a( void ) { uint8 i = 0; MEMBER_LIST( LOAD ) }
extern void InitGlobals_b( void );
int _tmain(int argc, _TCHAR* argv[])
{ InitGlobals_a();  InitGlobals_b();
return 0;
// file2.cpp -------------------------------------------
#define MEMBER_LIST( Usage ) \
Usage( y1 ) \
Usage( y2 )
#define IMPORT( ext_member ) extern Number ext_member;
#define COUNT( member ) 1 +
#define LOAD( member_val ) b[ i++ ] = member_val;
Number x1 = 33, x2 = 55;
MEMBER_LIST( IMPORT )
static Number b[ MEMBER_LIST( COUNT ) 0 ];
void InitGlobals_b( void ) { uint8 i = 0;  MEMBER_LIST( LOAD ) }
Of course, something like
#define MEMBER_LIST( Usage ) Usage( x1 ) Usage( x2 )
could be further simplified using other macros so you can simple use
#define MEMBER_LIST x1, x2
but those additional macros will add up to the complexity.

Similar Messages

  • Calling a method from another file

    This is pretty basic stuff but i can't seem to get it right. I am calling a method from another file. The other file IS located in the same folder BUT when i compile i get errors
    "cannot find symbol" <===referring to limit and sieve i believe.
    The method name is "sieve" the file name is "PrimeSieve2008" and "limit" is the variable in brackets in the real method.
         public static void main (String [] args) {
    final int [] PRIMES;
    int sieve = PrimeSieve2008.sieve(limit);
         PRIMES = sieve(getValidInt());
              for (int j = 0; j<PRIMES.length; j++) {
                   System.out.println("Prime[" + j + "] = " + PRIMES[j]);
    Is "int sieve = PrimeSieve2008.sieve(limit)" the wrong way to call a file?
    Thanks a million,
    Alex
    Edited by: Simplistic2099 on Apr 3, 2008 7:47 PM
    Edited by: Simplistic2099 on Apr 3, 2008 7:49 PM

    Simplistic2099 wrote:
    the other method runs fine:
    "public static int[] sieve(final int limit){
    int candidate; // possible prime
    int count; // no. of primes found
    boolean[] mayBePrime = new boolean[limit+1];
    // remaining possibilities
    final int[] PRIMES; // array to return
    // initialize mayBePrime
    for ( int j = 0 ; j <= limit ; j++ ) {
    mayBePrime[j] = true;
    mayBePrime[0] = mayBePrime[1] = false;
    // apply sieve, and count primes
    candidate = 2;
    count = 0;
    while ( candidate <= limit ) {
    if ( mayBePrime[candidate] ) {
    count++;
    for ( int j = 2 * candidate ; j <= limit ; j += candidate ) {
    mayBePrime[j] = false;
    } // end for
    } // end if
    candidate++;
    } // end while
    // fill up new array with the primes found
    PRIMES = new int[count];
    count = 0;
    for (int j = 2 ; j <= limit ; j++ ) {
    if ( mayBePrime[j] ) {
    PRIMES[count] = j;
    count++;
    } // end if
    } // for
    return PRIMES;
    } // sieve
    I really am clueless here.in this one you are passing in limit.
    in the other one you are getting limit from somewhere outside of main.

  • When clicked on an icon in the infopath form, it will open another infopath form from another file. How do?

    When clicked on an icon in the infopath 2013 form, it will open another infopath 2013 form from another
    file. How do?

    Hello Eugene Astafiev!
    I need the following scenario: 
    I have a Sharepoint library with items created by Infopath (form A). 
    I developed another form (form B) that will query items created by form A. 
    The form B will be in a static "webpart" page navigation (Sharepoint). One of these fields returned by the query library that manages the items created is the URL responsible to load the item data . I would like to parameterize the URL into form B.
    So that when the user clicks on it, the form A with their respective data in a modal is returned (which may be a native modal Sharepoint)

  • Insert Pages From another File?

    HI Everyone,
    Is there a way I can insert entire pages from one file into another?
    I'm working on a document and need several pages from another file - is there a way I can import or insert?
    Cheers
    Darryn

    Open your files & show thumbnails. Sections have a yellow border around all of the pages in that section. Now click on the page in the thumbnail pane & copy. If the file is more than one page & you only want one, you'll need to insert a section break to separate the pages. Then go to your other file, click in the thumbnail pane & paste. The whole copied page will be pasted in. Repeat with another section. Styles will copy over with the sections but headers & footers will not.

  • Js load xml element - style match from another file

    Hi all
    I got a ID file with a placed xml file, all styles are prepaired.
    Now I would like to load the xml element <-> style match from a given template file, where I prepaired all the matches.
    I would imagine this is a bit like loading the styles or the swatches from another file, but have not found any code samples yet.
    Can anybody help?
    Thanks
    Romano

    js for Structure; XML; Map Tags to Styles...
    I don't think that is what I am looking for and I feel I must asked this question in an unclear way...
    so I started a new discussen with the above heading.
    Thank you anyway.
    Romano

  • How do you sync music into your library from another file

    how do you sync music into your library from another file?  After moving all my music into a new location, is there a quicker way to upload the music into the library rather than adding file by file?

    Hi MonicaJani,
    Thanks for using Apple Support Communities.  You can also add folders of media as described here:
    Adding music and other content to iTunes
    http://support.apple.com/kb/ht1473
    Adding content on your computer to iTunes
    iTunes helps you add digital audio and video files on your computer directly to your iTunes library. You can add audio files that are in AAC, MP3, WAV, AIFF, Apple Lossless, or Audible.com (.aa) format. If you have unprotected WMA content, iTunes for Windows can convert these files to one of these formats. You can also add video content in QuickTime or MPEG-4 format to iTunes. To learn how to add these files to iTunes follow the steps below.
    Open iTunes
    From the File menu, choose one of the following choices:
    MacAdd to Library
    Windows
    Add File to Library
    Add Folder to Library
    Navigate to and select the file or folder that you want to add
    If iTunes is set to "Copy files to the iTunes Music folder when adding to library," iTunes will copy all content that is added to the iTunes library to the iTunes Music folder. To adjust this setting or change the location of this folder, go to the Advanced tab in iTunes Preferences.
    Cheers,
    - Ari

  • Copy standard cost with Cost Component from another material

    Hi,
    I need to copy standard cost from another material not only total price but also details of cost component split. I try to used transaction CKUC with procedure of "explode material cost estimate" but the reference material use "mixed costing" and isystem stop explosion.
    There is another procedure in order to make this copy? I can not use special procurement because are different codes (material A / Plant XXX copy froma material B /Plant XXX).
    Thanks for your support.
    Mic

    Hi Chandra,
    thanks for your suggestion, it works but only if I explode a level ... material "B" contains two mix codes  that also contain their mixes. So system shows this message "Mixed cost estimate explosion in level 2 for material xxx" and "Mixed cost estimate exists: maximum of 2 explosion level (s) possible".
    So Is not possible to copy and esploded a standard cost with multi level mix?
    Thanks
    Michela

  • Read group membership for a user object and populate every group with matching user from another domain

    I have LON\JSmith in LON domain and DEL\JimSmith in DEL domain
    I would like to extract group memberships of LON\JSmith in LON domain and append matching by email (i.e. DEL\JimSmith) user object in every group in LON domain.
    for instance
    LON\JSmith and DEL\JimSmith is the same person and has same email address [email protected]
    LON\JSmith belongs to 3 groups - LON\localadmingroup;LON\univdesktop;LON\globalsurvey
    The outcome of the script should be
    LON\JSmith; DEL\JimSmith    should be in 3 groups - LON\localadmingroup;LON\univdesktop;LON\globalsurvey.
    How can i do it?
    Navgup

    Hi Navgup,
    Please refer to the script below, to query users in other domain by specifying the parameter "-Server" in the cmdlet "get-aduser", and also note I haven't tested the script below:
    import-module activedirectory
    get-adgroupmember "group"|foreach{
    $email=(get-aduser $_.samaccountname -properties *).EmailAddress#get the user email
    Get-ADUser -filter {EmailAddress -eq $email} -properties * -server DomainB.company.com|select samaccountname, memberof}#filter user name and group with the email in other domain
    To get users across domain, please also refer this blog:
    Adding/removing members from another forest or domain to groups in Active Directory:
    http://blogs.msdn.com/b/adpowershell/archive/2010/01/20/adding-removing-members-from-another-forest-or-domain-to-groups-in-active-directory.aspx?Redirected=true
    I hope this helps.

  • UPDATING A TABLE WITH SAME INFO FROM ANOTHER TABLE ON THE SAME DB

    0down votefavorite
    I am trying to update a table with info from another table on the same db with same table name. I just want the info to be the same , no primary key or constraint involve just a straight replacement of records and I keep getting errors WITH THE TABLE not
    being recignize. below is my query:
    UPDATE
    VNDFIL
    SET EOBTYP
    =  VNDFIL.EOBTYP, 
    EDI_X12_835_VERSION =  VNDFIL.EDI_X12_835_VERSION
    FROM
    AGERECOVERY
    WHERE
    VNDFIL.EOBTYP
    = VNDFIL.EOBTYP
    AND
    VNDFIL
    .EDI_X12_835_VERSION
    = VNDFIL.EDI_X12_835_VERSION

    Hi rotary,
    If those two same named tables are in the same database then they have to be in different schemas. If you mean they are in the same server instance, then they may be in different databases, besides the "table not being recognized" error,
    anyway you should use the fully qualified table names, that is database.Schema.Table(If across instances, ServerName should be prefixed) to avoid the table unrecognized error.
    Using Identifiers As Object Names
    With the fully qualified names, your update statement can be like below.
    UPDATE
    db1.schema1.VNDFIL
    SET EOBTYP = srcTbl.EOBTYP, EDI_X12_835_VERSION = srcTbl.EDI_X12_835_VERSION
    FROM
    db1.schema2.VNDFIL srcTbl
    WHERE
    db1.schema1.VNDFIL.EOBTYP = srcTbl.VNDFIL.EOBTYP AND
    db1.schema1.VNDFIL.EDI_X12_835_VERSION = srcTbl.VNDFIL.EDI_X12_835_VERSION
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Problem with creating site from another computer!

    Hi
    I have WebDB 2.2 and Oracle8i instaled on the same computer. I have a problem to create site from another computer. There is not any process when I try to create site. There is always 0%.
    But I have no problem with creating site on the origin computer.
    Does anybody know something about it?

    I am just not clear what to do once I have made changes and have published the new information.
    You shouldn't have to do anything. iWeb will save the information in the Domain.sites file. You can keep this file in a folder, or even on your desktop and iWeb will launch from a double-click on the file.

  • Breakout table (fill table with matching data from another table)

    Hi
    I've been trying to study old discussions about breakout tables. I feel I'm close, but still no cigar :-)
    In plain english, I'm trying to autocreate rows with data on a table, based on matching values from another table. E.g. have a table to display all rows where type = AssetX
    I have attached a screenshot of my "master table" called Assets:
    I'm looking to prefill Asset name, Total from this table and populate a new table called e.g. Greenhouse
    Where I'd be adding more data (date, income, expense).
    Any help whould be greatly appreciated.
    Thanks!

    Hi,
    Here is a Sample Query.
    Update Emp A
    Set Sal = (Select Sal from emp b where
    a.empno = b.empno)
    where empno in (select empno from emp);
    Regards,
    Ganesh R
    null

  • Count with a conditional from another DATASET

    Hi guys!
    How could I count records in a table from another Dataset? I tried this, but I got syntaxis error on the comma that indicates the dataset. Please.
    =Count(IIf((Fields!new_leadsourceid.Value, "AllNewLeads") = Fields!new_leadsourceid.Value, 1, Nothing))
    Thank you.

    What do you mean "bring the data by groups"? And "total
    count, but divided by groups", do you mean you want an average across multiple input arrays?
    The Lookup expressions can be scoped to any valid scope. What is a valid scope depends on the context. If I put a Lookup expression in a table cell that is contained within a group, a valid scope is that group or any parent group up to and including the
    table's dataset.
    The custom code can be modified to accommodate multiple groups in the input and to return the total elements from all input arrays. The restrictions on custom code are the assemblies available on the server(s) where the code will execute. In most cases,
    server admins are reluctant to add custom assemblies or additional packages to their server. As long as you restrict your the code to use only what is available in the core .Net assemblies, it shouldn't be a problem. This custom code shouldn't be a problem
    for that.
    "You will find a fortune, though it will not be the one you seek." -
    Blind Seer, O Brother Where Art Thou
    Please Mark posts as answers or helpful so that others may find the fortune they seek.

  • Controlling a SubVI with while loop from another VI

    Dear All,
    this might be an easy Question but i couldn't catch an answer for it.
    first of all i have a VI which i will use as a subVI , this VI  is simply as shown in the "test_out of scope.vi" attached file
    now i will use it inside another VI called "Main VI" as shown in the file "Main_VI.vi"
    i'm just wondering , why couldn't i control the "Frequency" and "Stop" as i can do so while running the SubVI only without accessing it from another VI ?
    isn't it possible to access objects inside a while loop from another VI if i just connected them in the connection Pane terminals ??
    Thanks in advance to everybody
    Message Edited by Mohammed.Ashraf on 06-09-2009 10:27 AM
    Eng. Mohammed Ashraf
    Certified LabVIEW Associated Developer
    InnoVision Systems Founder, RF Test Development Engineer
    www.ivsystems-eg.com
    Attachments:
    Main_VI.vi ‏10 KB
    test_out of scope.vi ‏30 KB

    Do you need the sub-vi to run iterations for an undertermined period of time? 
    If so, then why not implement it as a parallel loop to the main one.  Maybe part of a consumer loop.
    If not.  Where the main loop would take care of each iteration and call the sub-vi in one shot. Then no need for a loop in the sub-vi.  
    It's all a matter of how you want the software to behave.  Have you looked at Event Structures?
    R

  • Using the eyedropper tool to take a color from another file or website...

    Hi,
    I'm new to Kuler, but recall being able to use the eyedropper tool in InDesign and click on an area of color from a file from another application or a website and have use it in the InDesign file.
    Am I incorrect?
    If there is a way to do what I am asking if you could please explain how I'd really appreciate it.
    Thanks and look forward to hearing back from you soon.

    Not sure what exactly you are asking here.
    However, wrt Kuler in Indesign, You can add swatches to Indesign Swatches Panel. You can apply color to ID Fill/Stroke color by simply double-clicking a color on Create Tab inside Kuler panel. Or you can take color from Fill/Stroke and set it as base in Create tab to create theme around it

  • A problem with TEXT READING from a file

    Hi all,
    I've been trying to parse a text file, read it line by line and then write it line by line in another file. I use BufferedReader and BufferedWriter.
    However, it seems that at each line it doesn't read the first character!!! How is this possible?
    Here is my piece of code:
    public class ParseMDL {
         public BufferedReader readMDL;
         public BufferedWriter writeMDL;
         public ParseMDL() {
              try {
                   writeMDL = new BufferedWriter(new FileWriter("mdlOUT.mdl", true));
              } catch (IOException e) {
                   System.out.println("Exception: Error with the output .mdl file!");
              try {
                   readMDL = new BufferedReader(new FileReader("subsystemblock.mdl"));
              } catch(FileNotFoundException e) {
                   System.out.println("Exception: Input .mdl file cannot be found!");
         public void executeMDLScanner() {
                   String strIN, strOUT = null;
                   try {
                        while(readMDL.read() != -1) {     
                             strIN = readMDL.readLine();
                             System.out.println(strIN);
                             if(strIN.contains("MaskPromptString")) {
                                       strOUT = "\t " + "MaskPromptString" + "\t     " + "newENTRIESSSS";
                                       System.out.println(strOUT);
                             //else just copy the line
                             else {
                                  strOUT = strIN;
                             try {
                                  writeMDL.write(strOUT);
                                  writeMDL.newLine();
                             } catch (IllegalArgumentException e) {
                                  System.out.println("Exception: Illegal Argument Exception");
                        writeMDL.close();
                        readMDL.close();
                   } catch(IOException e) {
                        System.out.println("Exception: IO exception!");
    }THANK YOU!
    Message was edited by:
    Pesho_318i
    Message was edited by:
    Pesho_318i

    Don't do this:while (readMDL.read() != -1) { // <-- reads the first character of the line
        strIN = readMDL.readLine(); // <-- reads the rest of the lineInstead do something like this:while ((strIN = readMDL.readLine()) != null) { // <--- reads all the line in one shot
        ...Regards

Maybe you are looking for