Modulinos: Difference between revisions

From Rosetta Code
Content added Content deleted
(First example)
 
(Added C++)
Line 1: Line 1:
{{task|Basic language learning}}[[Category: UNIX Shell]]
{{task|Basic language learning}}[[Category: UNIX Shell]]
It is useful to be able to run a main() function only when a program is run directly. This is a central feature in programming scripts; the feature is called /scripted main/.
It is useful to be able to run a main() function only when a program is run directly. This is a central feature in programming scripts; the feature is called /scripted main/.

Examples from [https://github.com/mcandre/scriptedmain GitHub].


=={{header|C}}==
=={{header|C}}==
Line 23: Line 25:
for (i = 0; i < argc; i++) {
for (i = 0; i < argc; i++) {
printf("Arg: %s\n", argv[i]);
printf("Arg: %s\n", argv[i]);
}

return 0;
}</lang>


=={{header|C++}}==
C++ programs also have scripted main by default.

<lang c++>#include <iostream>
#include <unistd.h>

using namespace std;

int main(int argc, char **argv) {
char cwd[1024];
getcwd(cwd, sizeof(cwd));

cout << "Directory: " << cwd << endl;

cout << "Program: " << argv[0] << endl;

cout << "Number of Args: " << argc << endl;

int i;
for (i = 0; i < argc; i++) {
cout << "Arg: " << argv[i] << endl;
}
}



Revision as of 23:26, 3 March 2011

Task
Modulinos
You are encouraged to solve this task according to the task description, using any language you may know.

It is useful to be able to run a main() function only when a program is run directly. This is a central feature in programming scripts; the feature is called /scripted main/.

Examples from GitHub.

C

C programs have scripted main by default; as long as main() is not included in the header file, this program's (empty) API is accessible by other C code.

<lang c>#include "scriptedmain.h"

  1. include <stdio.h>
  2. include <unistd.h>

int main(int argc, char **argv) { char cwd[1024]; getcwd(cwd, sizeof(cwd));

printf("Directory: %s\n", cwd);

printf("Program: %s\n", argv[0]);

printf("Number of Args: %d\n", argc);

int i; for (i = 0; i < argc; i++) { printf("Arg: %s\n", argv[i]); }

return 0; }</lang>


C++

C++ programs also have scripted main by default.

<lang c++>#include <iostream>

  1. include <unistd.h>

using namespace std;

int main(int argc, char **argv) { char cwd[1024]; getcwd(cwd, sizeof(cwd));

cout << "Directory: " << cwd << endl;

cout << "Program: " << argv[0] << endl;

cout << "Number of Args: " << argc << endl;

int i; for (i = 0; i < argc; i++) { cout << "Arg: " << argv[i] << endl; }

return 0; }</lang>