Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Language Reference

table of contents

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

Pragmas

Contents
  1. Predefined Pragmas
    1. pragma crt_constructor
    2. pragma crt_destructor
    3. pragma inline
    4. pragma lib
    5. pragma linkerDirective
    6. pragma mangle
    7. pragma msg
    8. pragma printf
    9. pragma scanf
    10. pragma startaddress
  2. Vendor Specific Pragmas
PragmaDeclaration:Pragma;PragmaDeclarationBlock
PragmaStatement:Pragma;PragmaNoScopeStatement
Pragma:pragma(Identifier)pragma(Identifier,ArgumentList)

Pragmas pass special information to the implementation and can add vendor specific extensions. Pragmas can be used by themselves terminated with a;, and can apply to a statement, a block of statements, a declaration, or a block of declarations.

Pragmas can be either aPragmaDeclaration or aPragmaStatement.

pragma(ident);// just by itselfpragma(ident) declaration;// influence one declarationpragma(ident):// influence subsequent declarations    declaration;    declaration;pragma(ident)// influence block of declarations{    declaration;    declaration;}pragma(ident) statement;// influence one statementpragma(ident)// influence block of statements{    statement;    statement;}

The kind of pragma it is determined by theIdentifier.ArgumentList is a comma-separated list ofAssignExpressions. TheAssignExpressions must be parsable as expressions, but their meaning is up to the individual pragma semantics.

Predefined Pragmas

All implementations must support these, even if by just ignoring them:

Implementation Defined: An implementation may ignore these pragmas.

pragma crt_constructor

Annotates a function so it is run after the C runtime library is initialized and before the D runtime library is initialized.

The function must:

  1. beextern (C)
  2. not have any parameters
  3. not be a non-static member function
  4. be a function definition, not a declaration (i.e. it must have a function body)
  5. not return a type that has a destructor
  6. not be a nested function
__gsharedint initCount;pragma(crt_constructor)extern(C)void initializer() { initCount += 1; }

No arguments to the pragma are allowed.

A function may be annotated with bothpragma(crt_constructor) andpragma(crt_destructor).

Annotating declarations other than function definitions has no effect.

Annotating a struct or class definition does not affect the members of the aggregate.

A function that is annotated withpragma(crt_constructor) may initializeconst orimmutable variables.

Best Practices: Use for system programming and interfacing with C/C++, for example to allow for initialization of the runtime when loading a DSO, or as a simple replacement forshared static this inbetterC mode.
Implementation Defined: The order in which functions annotated withpragma(crt_constructor) are run is implementation defined.
Best Practices: to control the order in which the functions are called within one module, write a single function that calls them in the desired order, and only annotate that function.
Implementation Defined: This uses the mechanism C compilers use to run code beforemain() is called. C++ compilers use it to run static constructors and destructors. For example, GCC's__attribute__((constructor)) is equivalent. Digital Mars C uses_STI and_STD identifier prefixes to mark crt_constructor and crt_destructor functions.
Implementation Defined: A reference to the annotated function will be inserted in the.init_array section for Elf systems, theXI section for Win32 OMF systems, the.CRT$XCU section for Windows MSCOFF systems, and the__mod_init_func section for OSX systems.
Note:crt_constructor andcrt_destructor were implemented inv2.078.0 (2018-01-01). Some compilers exposed non-standard, compiler-specific mechanism before.

pragma crt_destructor

pragma(crt_destructor) works the same aspragma(crt_constructor) except:

  1. Annotates a function so it is run after the D runtime library is terminated and before the C runtime library is terminated. Calling C'sexit() function also causes the annotated functions to run.
  2. The order in which the annotated functions are run is the reverse of those functions annotated withpragma(crt_constructor).
Implementation Defined: This uses the mechanism C compilers use to run code aftermain() returns orexit() is called. C++ compilers use it to run static destructors. For example, GCC's__attribute__((destructor)) is equivalent. Digital Mars C uses_STI and_STD identifier prefixes to mark crt_constructor and crt_destructor functions.
Implementation Defined: A reference to the annotated function will be inserted in the.fini_array section for Elf systems, theXC section for Win32 OMF systems, the.CRT$XPU section for Windows MSCOFF systems, and the__mod_term_func section for OSX systems.
__gsharedint initCount;pragma(crt_constructor)extern(C)void initialize() { initCount += 1; }pragma(crt_destructor)extern(C)void deinitialize() { initCount -= 1; }pragma(crt_constructor)pragma(crt_destructor)extern(C)void innuendo() { printf("Inside a constructor... Or destructor?\n"); }

pragma inline

Affects whether functions are inlined or not. If at the declaration level, it affects the functions declared in the block it controls. If inside a function, it affects the function it is enclosed by.

It takes two forms:

  1. pragma(inline)
    Sets the behavior to match the implementation's default behavior.
  2. pragma(inline, AssignExpression)
    TheAssignExpression is evaluated and must have a type that can be converted to a boolean. If the result is false the functions are never inlined, otherwise they are always inlined.

More than oneAssignExpression is not allowed.

If there are multiple pragma inlines in a function, the lexically last one takes effect.

pragma(inline):int foo(int x)// foo() is never inlined{pragma(inline,true);    ++x;pragma(inline,false);// supercedes the othersreturn x + 3;}
Implementation Defined:
  1. The default inline behavior is typically selectable with a compiler switch such as-inline.
  2. Whether a particular function can be inlined or not is implementation defined.
  3. What happens forpragma(inline, true) if the function cannot be inlined. An error message is typical.

pragma lib

There must be oneAssignExpression and it must evaluate at compile time to a string literal.

pragma(lib,"foo.lib");
Implementation Defined: The string literal specifies the file name of a library file. This name is inserted into the generated object file, or otherwise passed to the linker, so the linker automatically links in that library.

pragma linkerDirective

There must be oneAssignExpression and it must evaluate at compile time to a string literal.

pragma(linkerDirective,"/FAILIFMISMATCH:_ITERATOR_DEBUG_LEVEL=2");
Implementation Defined: The string literal specifies a linker directive to be embedded in the generated object file. Linker directives are only supported for MS-COFF output.

pragma mangle

Overrides the default mangling for a symbol.

For variables and functions there must be oneAssignExpression and it must evaluate at compile time to a string literal. For aggregates there may be one or twoAssignExpressions, one of which must evaluate at compile time to a string literal and one which must evaluate to a symbol. If that symbol is aTemplateInstance, the aggregate is treated as a template that has the signature and arguments of theTemplateInstance. The identifier of the symbol is used when no string is supplied. Both arguments may be used used when an aggregate's name is a D keyword.

It only applies to function and variable symbols. Other symbols are ignored.

Implementation Defined: On macOS and Win32, an extra underscore (_) is prepended to the string since 2.079, as is done by the C/C++ toolchain. This allows using the samepragma(mangle) for all compatible (POSIX in one case, win64 in another) platforms instead of having to special-case.
Rationale:
  • Enables linking to symbol names that D cannot represent.
  • Enables linking to a symbol which is a D keyword, since anIdentifier cannot be a keyword.
pragma(mangle,"body")extern(C)void body_func();pragma(mangle,"function")extern(C++)struct _function {}template ScopeClass(C){pragma(mangle, C)struct ScopeClass {align(__traits(classInstanceAlignment, C))void[__traits(classInstanceSize, C)] buffer; }}extern(C++){class MyClassA(T) {}void func(ref ScopeClass!(MyClassA!int));// mangles as MyClass<int>&}

pragma msg

EachAssignExpression is evaluated at compile time and then all are combined into a message.

pragma(msg,"compiling...", 6, 1.0);// prints "compiling...61.0" at compile time
Implementation Defined: The form the message takes and how it is presented to the user. One way is by printing them to the standard error stream.
Rationale: Analogously to howwriteln() performs a role of writing informational messages during runtime,pragma(msg) performs the equivalent role at compile time. For example,
staticif (kilroy)pragma(msg,"Kilroy was here");elsepragma(msg,"Kilroy got lost");

pragma printf

pragma(printf) specifies that a function declaration is a printf-like function, meaning it is anextern (C) orextern (C++) function with aformat parameter accepting a pointer to a 0-terminatedchar string conforming to the C99 Standard 7.19.6.1, immediately followed by either a... variadic argument list or a parameter of typeva_list as the last parameter.

If theformat argument is a string literal, it is verified to be a valid format string per the C99 Standard. If theformat parameter is followed by..., the number and types of the variadic arguments are checked against the format string.

Diagnosed incompatibilities are:

Per the C99 Standard, extra arguments are ignored.

Ignored mismatches are:

printf("%k\n", value);// error: non-Standard format kprintf("%d\n");// error: not enough argumentsprintf("%d\n", 1, 2);// ok, extra arguments ignored
Best Practices: In order to use non-Standard printf/scanf formats, an easy workaround is:
const format ="%k\n";printf(format.ptr, value);// no error
Best Practices: Most of the errors detected are portability issues. For instance,
string s;printf("%.*s\n", s.length, s.ptr);printf("%d\n", s.sizeof);ulong u;scanf("%lld%*c\n", &u);
should be replaced with:
string s;printf("%.*s\n",cast(int) s.length, s.ptr);printf("%zd\n", s.sizeof);ulong u;scanf("%llu%*c\n", &u);

pragma(printf) applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type.

pragma scanf

pragma(scanf) specifies that a function declaration is a scanf-like function, meaning it is anextern (C) orextern (C++) function with aformat parameter accepting a pointer to a 0-terminatedchar string conforming to the C99 Standard 7.19.6.2, immediately followed by either a... variadic argument list or a parameter of typeva_list as the last parameter.

If theformat argument is a string literal, it is verified to be a valid format string per the C99 Standard. If theformat parameter is followed by..., the number and types of the variadic arguments are checked against the format string.

Diagnosed incompatibilities are:

Per the C99 Standard, extra arguments are ignored.

pragma(scanf) applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type.

pragma startaddress

There must be oneAssignExpression and it must evaluate at compile time to a function symbol.

Implementation Defined: The function symbol specifies the start address for the program. The symbol is inserted into the object file or is otherwise presented to the linker to set the start address. This is not normally used for application level programming, but is for specialized systems work. For applications code, the start address is taken care of by the runtime library.
void foo() { ... }pragma(startaddress, foo);

Vendor Specific Pragmas

Vendor specific pragmaIdentifiers can be defined if they are prefixed by the vendor's trademarked name, in a similar manner to version identifiers:

pragma(DigitalMars_extension) { ... }

Implementations must diagnose an error for unrecognizedPragmas, even if they are vendor specific ones.

Implementation Defined: Vendor specific pragmas.
Best Practices: vendor specific pragmas should be wrapped in version statements
version (DigitalMars){pragma(DigitalMars_extension)    {   ... }}
Attributes
Expressions
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Thu Feb 19 20:55:41 2026

[8]ページ先頭

©2009-2026 Movatter.jp