2

I know that it is always the main () function being executed first, then function calls will direct the program to other functions. What if functions were called *before* the main () function? When will they be executed?\

I had a program (I downloaded from the Internet) and there were function calls before main( ).

Now I don't know what they are for if execution is only done in main () (and the the functions called inside main).

HERE IS THE FRAGMENT OF THE PROGRAM:

static void set_level_indices   (VideoParameters *p_Vid);
static void chroma_mc_setup     (VideoParameters *p_Vid);
static void init_img            (VideoParameters *p_Vid);
static void init_encoder        (VideoParameters *p_Vid, InputParameters *p_Inp);
static int  init_global_buffers (VideoParameters *p_Vid, InputParameters *p_Inp);
static void free_global_buffers (VideoParameters *p_Vid, InputParameters *p_Inp);
static void free_img            (VideoParameters *p_Vid, InputParameters *p_Inp);
static void free_params         (InputParameters *p_Inp);

static void encode_sequence     (VideoParameters *p_Vid, InputParameters *p_Inp);

*(SOME FUNCTION DECLARATIONS OMITTED)*

int main(int argc, char **argv)
{
  init_time();
#if MEMORY_DEBUG
  _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

  alloc_encoder(&p_Enc);

  Configure (p_Enc->p_Vid, p_Enc->p_Inp, argc, argv);

  // init encoder
  init_encoder(p_Enc->p_Vid, p_Enc->p_Inp);

  // encode sequence
  encode_sequence(p_Enc->p_Vid, p_Enc->p_Inp);

  // terminate sequence
  free_encoder_memory(p_Enc->p_Vid, p_Enc->p_Inp);

  free_params (p_Enc->p_Inp);  
  free_encoder(p_Enc);

  return 0;
}

Now that I thought of it, is the static has something to do with these calls done before main () being okay?

This is the encoder of H.264 in its reference software.

EDIT

Are the codes above main () function calls, function prototypes or a function declaration. You all give different answers. Please choose one and explain why by presenting the format. I really thought these statements are in the form of function calls. Furthermore, can function prototypes be included in a source code and not in the header file? Thank you!

mc8
  • 215
  • 7
  • 20
  • 4
    Your question doesn't make sense. You said "I know that it is always the main() function being executed first." That means nothing else will be called before it. – Barmar Jun 29 '13 at 03:11
  • Since execution begins with `main()` how will these functions be called before that? –  Jun 29 '13 at 03:12
  • what will happen to the functions called before the main () function? I have this program (not mine) and many function were CALLED before main(). What is the sense of putting these function calls there if they will not be executed? – mc8 Jun 29 '13 at 03:13
  • … like `crt0` or `ld` prelinkers and so forth, perhaps … ? – BRPocock Jun 29 '13 at 03:14
  • You say `functions are called inside main`. So how do you expect them to be executed before main()? can you post the link to the code? – Aswin Murugesh Jun 29 '13 at 03:18
  • 6
    You might be misinterpreting what you see. It's okay for other function bodies to __appear__ before `main()` in the source text. Program execution doesn't proceed from top-to-bottom, the `main()` function will be the entry point when the program is executed. – Blastfurnace Jun 29 '13 at 03:19
  • no, not really. these functions called before main () can be found in another source file (the function declaration). – mc8 Jun 29 '13 at 03:19
  • Clarification request: When you say "function calls before main" do you mean you saw calls in the source code that happened to be appear textually before the definition of main, or do think the calls happen before main is called? – Ray Toal Jun 29 '13 at 03:20
  • I don't know who's more confused, you or me. – Mortimer McMire Jun 29 '13 at 03:21
  • so if it is not top-to-bottom nor it is sequential, and execution always begin with main() what will happen to these function calls? @Blastfurnace – mc8 Jun 29 '13 at 03:21
  • @mc8 Why not show some code so that we can see what you mean really? – Yu Hao Jun 29 '13 at 03:21
  • @RayToal the calls were made before the DEFINITION of main () – mc8 Jun 29 '13 at 03:22
  • Nobody can answer that because you haven't posted this mysterious code. – Blastfurnace Jun 29 '13 at 03:23
  • @mc8: What do you mean by "calls were made before the DEFINITION of main()". Are you running C in an interpreter? – jxh Jun 29 '13 at 03:34
  • @jxh I don't know what that means. I'm using Visual Studio 2012 Ultimate. – mc8 Jun 29 '13 at 03:41
  • What you see are __function prototypes__. I suggest you spend some time with a good [C Book from this list](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Blastfurnace Jun 29 '13 at 03:49
  • these are function prototypes? i thought function prototypes only contain the data type in their argument? I'm confused. @Blastfurnace – mc8 Jun 29 '13 at 03:54

7 Answers7

14

If you are asking how this might be accomplished, it is not through a standard feature of the C language.

The C runtime works by providing an entry point for the operating system to execute when you execute the binary. That entry point runs code specific to the compiler implementation. It will set up some initialization code, and then call your main() function (with any command line parameters if provided). Any other code outside of the C runtime proper that is executed before main() is called is a mechanism outside of the C language (or an extension to the C language provided by the compiler).

In C++, global constructors are executed before main().

In C, your compiler implementation may provide an extension that allows a function to be marked to be executed before main() is called. In GCC, this can be done with the constructor attribute.

void foo () __attribute__((constructor));
void foo () { puts(__func__); }
int main () { puts(__func__); return 0; }

The output of the above program (when compiled with GCC) is:

foo
main
jxh
  • 64,506
  • 7
  • 96
  • 165
  • I'm using Visual Studio 2012. – mc8 Jun 29 '13 at 03:33
  • What if I have several projects (4 projects) in my Solution? and there are many source files and header files. Is there only one main () function? – mc8 Jun 29 '13 at 03:39
  • 1
    I don't know if it answers the question, but it enlightened me. – Yu Hao Jun 29 '13 at 03:40
  • @mc8: Yes. There is only one `main()`. – jxh Jun 29 '13 at 03:40
  • for each project or the entire solution? – mc8 Jun 29 '13 at 03:50
  • One per executable, however that maps to your build environment. Also, stop morphing your question. Arguments in a function prototype may or may not be named. – jxh Jun 29 '13 at 04:07
  • @jxh how can you call the function then? as compared to function prototypes. Can function prototypes appear in a source code? I thought it is placed in the header file. – mc8 Jun 29 '13 at 04:09
  • Header files get included. When included, the contents of that header file becomes part of the source file. – jxh Jun 29 '13 at 04:12
  • @jxh am I right? Is the format of function prototypes and function calls equivalent. However function prototypes are place outside main () while function calls inside main ()? – mc8 Jun 29 '13 at 04:20
  • What do you mean by " Any other code outside of the C runtime proper that is executed before main() is called is a mechanism outside of the C language (or an extension to the C language provided by the compiler). In C++, global constructors are executed before main(). In C, your compiler implementation may provide an extension that allows a function to be marked to be executed before main() is called. In GCC, this can be done with the constructor attribute." ? – mc8 Jun 29 '13 at 04:21
  • A function prototype is a declaration and looks just like a function definition, but without the function body, and is ended with a semicolon. A function call is an expression and passes values. – jxh Jun 29 '13 at 04:43
  • Regarding "What do you by...", it means that C doesn't support the notion of running code before `main()`. If you observe output from your program that shows otherwise, then either it is not C (e.g. it is C++), or it is being accomplished through some extension to the C language provided by the compiler. I then describe a feature of C++ that does it, and an extension provided by GCC that does it. – jxh Jun 29 '13 at 06:57
5

In the code that you have posted, the functions are declared before the main and that doesn't mean that these functions are called. They are declared, informing the compiler that those functions are going to be used in the program

Aswin Murugesh
  • 9,508
  • 10
  • 34
  • 65
3

In the code you listed, the functions before main are function prototypes, also called function declarations (they are synonyms). They are not function calls. You can tell they aren't function calls for two reasons:

  1. Functions cannot be called from the global scope. The global scope is anything outside of a function body. This is the quickest way to recognize it, but it's a little hand wavy.
  2. The real reason is that function calls are not preceded by type specifiers or type qualifiers, like void and static. These keywords specify the type of a symbol, in this case the function being declared. Function calls don't have a type (the return value does, but not the call itself), so you would never specify the type this way for a function call.

To answer some of your other questions:

  • In most implementations (and according to the C standard) the first user defined function to be executed is always main, in which case it is not possible for you to write code that calls any other function before main. In most cases, compilers will generate their own initialization code which is executed before your main function. It does things like set up memory and initialize static variables. In some cases, you can write code that will be used as part of initialization, but that's relatively uncommon and it would be compiler specific how to do that.
  • A function prototype, or function declaration, is just a way of telling the compiler about a function before you actually define/implement it. The declaration/prototype (same thing) tells the compiler: a) this symbol is a function, b) it has such-and-such return type, c) it has such-and-such parameter list. That way, when the compiler sees you try to call the function somewhere else in your code, it knows what you're trying to do.
  • The static keyword is called a storage specifier. On functions, it simply means that the function name is not exported to the linker, so it cannot be called from any other code modules (i.e., from any other C source files). So it's really just a way of limiting the visibility, or the scope, of the function.
  • Remember, a header file is just a way to include the same content in multiple places. Anywhere you #include a file, the compiler will treat it as if the contents of the included file appeared directly in the spot where it is included from. So function prototypes/declarations will very often appear in a header file. This allows the function to be "known" (and therefore called) from any source file where the header is included. Function implementations (also called function definitions) should generally not be put in header files. Doing so would cause the function to be defined every time the file is included, which will generally cause the linker to complain that the name (of the function) has multiple definitions. (The only way to get around that is marking the function static, and then you're really defining a file-local function each time the header is included, as opposed to implementing a single function with global scope which can be called from multiple source files. The latter is usually what you want.)
brianmearns
  • 8,433
  • 6
  • 49
  • 70
2

I think you may mis-understand function declarations and function calling.

#include <stdio.h>
void foo(void);
int main(void)
{
    printf("main\n");
    foo();
    return 0;
}
void foo(void)
{
    printf("func\n");
}

In the simple program above, since the definition of foo is below main, it has to be declared before main. Either put the declaration in a header file and include it, or, put the declaration before main or any function that calls them.

UPDATE:

functions that are static are just limited their scope in the file only, no other meanings.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
  • yes these functions were declared before main (). why do they have to be called before main? what effect does static have? what is their scope? – mc8 Jun 29 '13 at 03:46
  • @mc8 When they are declared, they are not **called**, you can run the simple program in my answer to test. `main` executes first. – Yu Hao Jun 29 '13 at 03:50
  • 2
    @mc8: Stop saying these are "called before main". You are seeing __function prototypes__. They simply tell the compiler that these functions are defined _somewhere_ and the number and type of their parameters. – Blastfurnace Jun 29 '13 at 03:53
  • @Blastfurnace how can these be function prototypes? please explain. isnt it that function prototypes have the form of: return_type function_name(data types of the arguments)? – mc8 Jun 29 '13 at 03:58
  • @mc8: Yes, don't let the `static` keyword or (optional) parameter names (`p_Vid`,`p_Inp`) confuse you. These are just function prototypes. – Blastfurnace Jun 29 '13 at 04:01
  • @Blastfurnace How are function prototypes different from function calls when it comes to format? How are they not considered as function calls? if you're going to call this function static void set_level_indices (VideoParameters *p_Vid); what is the format? – mc8 Jun 29 '13 at 04:04
  • @Blastfurnace so you can put the parameter names in a function prototype? how is this different from a function call? – mc8 Jun 29 '13 at 04:05
  • @mc8: Well for one difference, you don't specify the parameter `type` in a function call... Again, please read a [good C Book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list), this is a basic concept. – Blastfurnace Jun 29 '13 at 04:07
  • 1
    @mc8: You can think of "function prototype" and "function declaration" as synonymous. I tried to find a good SO question that might clarify the issue. [This is the best I found after a short search.](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) __FIXED LINK__ – Blastfurnace Jun 29 '13 at 04:26
  • So function declarations are not function definitions. okay. thanks! – mc8 Jun 29 '13 at 04:30
  • @Blastfurnace what best way do you suggest to understand a program that is not mine? I'm currently studying the H.264 (video compression) and the code is too complex. And I need to edit it to extend it to multivideo coding. Should I just debug it line by line? Thank you! – mc8 Jun 29 '13 at 04:36
  • @mc8: A video compression codec is a complex animal. I'd start at the highest level possible, trying to understand the overall data and control flow and existing functions. But this is a separate question... – Blastfurnace Jun 29 '13 at 04:42
  • that's what i'm doing now. are you familiar with h.264? – mc8 Jun 29 '13 at 04:45
1

Just write a print statement in each function..

printf(" main");

printf("function 1") etc

you will get the sequence of the functions being called. And by default the main function is always called first and at the end of execution the main functions should return back a int, float etc as declared in the main definition.

Pruthvi P
  • 516
  • 5
  • 29
0

If functions were called before the main function what would be the point of the main function? main is the starting point for the compiler in most languages.

If you want to run a function before the main() function code just call it before you run any code.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
Dummy Code
  • 1,758
  • 4
  • 18
  • 38
-1

If functions were called before the main function, they would execute before the main function.

David Schwartz
  • 166,415
  • 16
  • 184
  • 259
  • 1
    @Mehrdad: There was a story about a painter who was asked to paint an extraordinarily ugly woman. When he was done, the woman complained that the painting wasn't really a great work of art. The painter responded, "nor are you a great work of nature". – David Schwartz Jun 29 '13 at 03:28
  • The artist could have sketched (left a comment) instead of laboring away at a painting; saving the artist time and the lady money. – user2246674 Jun 29 '13 at 03:41
  • It's a bad answer because it's incorrect and misunderstands the basics of C execution. – brianmearns Jun 29 '13 at 04:29
  • 1
    @sh1ftst0rm If I'm incorrect, I'd really like to understand why. Can you give some more details? – David Schwartz Jun 29 '13 at 04:35
  • 2
    @sh1ftst0rm That's utter nonsense. The answer is tautological -- analytically correct -- and says nothing about the basics of C execution. And here's a piece of information for you: functions can be called before `main` and often are ... an implementation can do whatever it pleases before calling `main`, as long as it obeys the semantics of the C standard. – Jim Balter Jun 29 '13 at 04:40
  • @Mehrdad If so, that's a reflection on the question: "if functions were called *before* the main () function? When will they be executed?" – Jim Balter Jun 29 '13 at 04:48
  • @DavidSchwartz: ISO C standard (ISO/IEC 9899:1999), section 5.1.2.2.1: "The function called at program startup is named main". I will grant you that compiler's generally insert their our initialization code which runs before main is invoked, so fine, you are not technically incorrect. But that's clearly not what the OP was asking about and your answer was therefore not remotely helpful. – brianmearns Jun 29 '13 at 12:46
  • @sh1ftst0rm Moving the goalposts is evil. I don't have anything else to say to an evil person. – Jim Balter Jun 29 '13 at 13:35
  • @JimBalter. No idea what you mean by that, but that's fine. My guess is you encounter a lot of evil people in your life. – brianmearns Jun 29 '13 at 13:43
  • @sh1ftst0rm: When I gave my answer, it was not at all clear whether or not that was what the OP was asking about. In fact, I genuinely thought that was most likely what he was asking about, just like [jxh](http://stackoverflow.com/a/17376333/721269) did. The question appeared to be asking about functions being called before program startup, which is possible on almost all modern compilers. – David Schwartz Jun 30 '13 at 00:27
  • @DavidSchwartz: Fair enough. Looking at the history of the question, I agree your answer was ok when it was posted (although the question did say "I know that it is always the `main ()` function being executed first", indicating that the OP was confused about a few things). For the record, I'm not the one who downvoted it, though I don't disagree with it's score based on the question as it stands. If you revised your answer in light of the revised question, someone might upvote it again. – brianmearns Jun 30 '13 at 01:47