Skip to content

Bring in Cons' adding/overriding methods #3887

Open
@mwichmann

Description

@mwichmann

Until PR #3877 the User Guide documentation contained the following commented-out text, brought over from the Cons documentation, on the basis that we might want to add similar functionality someday and so it's useful to have it recorded somewhere. To keep the docs a little cleaner, and to actually make it easier to find, moving the text over to a Github Issue. Note SCons already has an AddMethod API.

Adding new methods

For slightly more demanding changes, you may wish to add new methods to the cons package. Here's an example of a very simple extension, InstallScript, which installs a tcl script in a requested location, but edits the script first to reflect a platform-dependent path that needs to be installed in the script:

  # cons::InstallScript - Create a platform dependent version of a shell
  # script by replacing string ``#!your-path-here'' with platform specific
  # path $BIN_DIR.

  sub cons::InstallScript {
	my ($env, $dst, $src) = @_;
	Command $env $dst, $src, qq(
		sed s+your-path-here+$BIN_DIR+ %< > %>
		chmod oug+x %>
	);
  }

Notice that this method is defined directly in the cons package (by prefixing the name with cons::). A change made in this manner will be globally visible to all environments, and could be called as in the following example:

  InstallScript $env "$BIN/foo", "foo.tcl";

For a small improvement in generality, the BINDIR variable could be passed in as an argument or taken from the construction environment, as %BINDIR.

Overriding methods

Instead of adding the method to the cons name space, you could define a new package which inherits existing methods from the cons package and overrides or adds others. This can be done using Perl's inheritance mechanisms.

The following example defines a new package cons::switch which overrides the standard Library method. The overridden method builds linked library modules, rather than library archives. A new constructor is provided. Environments created with this constructor will have the new library method; others won't.

  package cons::switch;
  BEGIN {@ISA = 'cons'}

  sub new {
	shift;
	bless new cons(@_);
  }

  sub Library {
	my($env) = shift;
	my($lib) = shift;
	my(@objs) = Objects $env @_;
	Command $env $lib, @objs, q(
		%LD -r %LDFLAGS %< -o %>
	);
  }

This functionality could be invoked as in the following example:

  $env = new cons::switch(@overrides);
  ...
  Library $env 'lib.o', 'foo.c', 'bar.c';

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions